logo

Как да конвертирате низове в стил 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++ стандартната библиотека съдържа функции и класове. 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 низовете (тъй като те са масив от знаци)
  • Те са лесни за работа. Операторът „+“ за конкатенация „=“ за присвояване може да се сравни с помощта на обикновени оператори.
  • низ::намери()и много други функции могат да бъдат реализирани на 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('%sn' 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('%sn' 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