C 스타일 문자열을 std::string으로 또는 그 반대로 변환하는 방법은 무엇입니까?

무엇입니까? C 스타일 문자열 ? 이러한 문자열은 NULL 문자로 끝나는 문자 배열입니다. C 스타일 문자열은 다음과 같은 방법으로 선언할 수 있습니다.

선언 및 초기화

CPP
   /* To demonstrate C style strings */   #include       using     namespace     std  ;   int     main  ()   {      /* Null character has to be added explicitly */      char     str1  [  8  ]     =     {  'H'          'E'          'L'          'L'          'O'           '-'    '1'    ''     };          /* Compiler implicitly adds Null character */      char     str2  []     =     'HELLO-2'     ;             /* Compiler implicitly adds Null character.     Note that string literals are typically stored    as read only */      const     char     *  str3     =     'HELLO-3'     ;      cout      < <     str1      < <     endl      < <     str2      < <     endl      < <     str3  ;      return     0  ;   }      
Output:
HELLO-1 HELLO-2 HELLO-3  
C style strings are operated with very useful functions like strcpy() strlen() strpbrk() 스트라치() 문자열() 그리고 더 많은 것!(이 모든 함수는 '의 멤버 함수입니다. cstring ' 헤더). std::string이란 무엇입니까? C++ 표준 라이브러리에는 함수와 클래스가 포함되어 있습니다. String은 클래스 중 하나입니다. 여기서는 문자열 클래스의 객체를 다룹니다. 이 std::string은 자체적으로 관리하고 자체 메모리를 관리합니다.

선언 및 초기화

CPP
   /* To demonstrate std::string */   #include       #include         using     namespace     std  ;   int     main  ()   {      /* s becomes object of class string. */      string     s  ;         /* Initializing with a value. */         s     =     'HELLO'  ;      /* Printing the value */         cout      < <     s  ;             return     0  ;   }   
Output:
HELLO  
C-String을 std::string으로 변환합니다. 그런데 왜 이런 변화가 필요한가? C 문자열에서 std::string으로? 왜냐하면
  • Std::string은 자체 공간을 관리합니다. 따라서 프로그래머는 C 문자열과 달리 메모리에 대해 걱정할 필요가 없습니다(문자 배열이므로).
  • 작동하기 쉽습니다. 연결을 위한 '+' 연산자 할당을 위한 '='는 일반 연산자를 사용하여 비교할 수 있습니다.
  • 문자열::찾기() C-String이 아닌 std::string에서 다른 많은 기능을 구현할 수 있으므로 이것이 편리합니다.
  • 반복자는 C 문자열이 아닌 std::string에서 사용할 수 있습니다.
And many more! Here is the code for it:- CPP
   /* To demonstrate C style string to std::string */   #include       using     namespace     std  ;   int     main  ()   {      /*Initializing a C-String */      const     char     *  a     =     'Testing'  ;         cout      < <     'This is a C-String : '   < <     a      < <     endl  ;      /* This is how std::string s is assigned    though a C string ‘a’ */      string     s  (  a  );             /* Now s is a std::string and a is a C-String */      cout      < <     'This is a std::string : '   < <     s      < <     endl  ;      return     0  ;   }   
Output:
This is a C-String : Testing This is a std::string : Testing  
The above conversion also works for character array.
 // Character array to std::string conversion char a[] = 'Testing'; string s(a);  
std::string을 C 스타일 문자열로 변환 왜 이런 변화가 필요한가요? std::string에서 C 문자열로?
  • 헤더에는 작업을 훨씬 쉽게 해주는 몇 가지 강력한 기능이 있기 때문입니다.
  • 끌고 가다() 초크() 그리고 더 많은 함수가 C 문자열에서만 작동합니다.
You can think of other reasons too! Here is the code for conversion:- CPP
   /* To demonstrate std::string to C style string */   #include       #include      /* This header contains string class */   using     namespace     std  ;   int     main  ()   {      /* std::string initialized */      string     s     =     'Testing'  ;         cout      < <     'This is a std::string : '   < <     s      < <     endl  ;      /* Address of first character of std::string is     stored to char pointer a */      char     *  a     =     &  (  s  [  0  ]);         /* Now 'a' has address of starting character    of string */      printf  (  '%s  n  '       a  );         return     0  ;   }   
Output:
This is a std::string : Testing This is a C-String : Testing  
std::string also has a function that can be used to get a null terminated character array. CPP
   /* To demonstrate std::string to C style string using    c_str() */   #include       using     namespace     std  ;   int     main  ()   {      /* std::string initialized */      string     s     =     'Testing'  ;         cout      < <     'This is a std::string : '   < <     s      < <     endl  ;      // c_str returns null terminated array of characters      const     char     *  a     =     s  .  c_str  ();      /* Now 'a' has address of starting character    of string */      printf  (  '%s  n  '       a  );         return     0  ;   }   
Output:
This is a std::string : Testing This is a C-String : Testing  
Both C strings and std::strings have their own advantages. One should know conversion between them to solve problems easily and effectively. 관련 기사: C++ 문자열 클래스 및 해당 응용 프로그램 | 세트 1 C++ 문자열 클래스 및 해당 응용 프로그램 | 세트 2