Як перетворити рядки стилю 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() strach() strstr() і багато іншого! (Усі ці функції є функціями-членами ' cstring ' заголовок ). Що таке std::string? Стандартна бібліотека C++ містить функції та класи. Рядок є одним із його класів. Тут ми маємо справу з об’єктом рядкового класу. Цей 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 (оскільки це масив символів)
  • Вони прості в експлуатації. Оператор «+» для конкатенації «=» для присвоєння можна порівняти за допомогою звичайних операторів.
  • string::find() і багато інших функцій можна реалізувати на std::string, а не на C-Strings, тому це стає зручним.
  • Ітератори можна використовувати в std::string, а не в C-рядках.
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 c_str() 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