C++——char* vs std::string vs char[]

  • char*

eg:char* str = "This is GeeksForGeeks";

pros:

  1. A pointer to the string, to save memory;
  2. Not need to specify the string size in advance.

cons:

  1. In the above example, the C language work, but C ++ will prompt warning, therefore, in C ++, to add const modifier. eg: const char * str = "This is GeeksForGeeks";
  2. C ++ is a constant string array of characters, it can not be modified.
  • std::string

std::string str = "This is GeeksForGeeks";

note:  std::string class which is an instantiation of the basic_string class template

pros:

  1. When devoted string, more convenient (searching, replacement, and manipulation functions)

However, there are some cases or more is recommended char * instead of std :: string

  1. Lower-level access processing, such as communication with the operating system
  2. Compatibility with older code C
  3. Save memory
  • char[]

eg: char str[] = "This is GeeksForGeeks";

pros:

  1. Modify the string

cons:

  1. This is a statically allocated array size, the space occupied by the stack.
  2. If we want to connect or operate with other strings, we need to open up large arrays, because of the size of the string is fixed. To this end, we can use the C ++ Standard Library cstring or string.h.

 

reference:https://www.geeksforgeeks.org/char-vs-stdstring-vs-char-c/

发布了56 篇原创文章 · 获赞 10 · 访问量 6821

Guess you like

Origin blog.csdn.net/qq_22148493/article/details/88362568