- char*
eg:char* str = "This is GeeksForGeeks";
pros:
- 一个指针指向字符串,节省内存;
- 不需要提前指定字符串大小。
cons:
- 上述例子在C语言中work,但是C++会有warning提示,因此,在C++中,要加const修饰。eg:const char* str = "This is GeeksForGeeks";
- C++中字符串都是常量字符数组,不能够被修改。
- std::string
std::string str = "This is GeeksForGeeks";
note: std::string class which is an instantiation of the basic_string class template
pros:
- 专门处理string时,更加方便(searching, replacement, and manipulation functions)
但是,有一些cases还是更推荐用char* 而不是std::string
- 处理较低级别的访问时,如与操作系统通信
- 与旧C代码的兼容性
- 节省内存
- char[]
eg: char str[] = "This is GeeksForGeeks";
pros:
- 修改字符串
cons:
- 这是静态分配大小的数组,占用堆栈中的空间。
- 如果我们想要与其他字符串连接或操作,我们需要采用开辟大的数组,因为字符串的大小是固定的。为此,我们可以使用C ++标准库cstring或string.h。
reference:https://www.geeksforgeeks.org/char-vs-stdstring-vs-char-c/