C++ string
main points:
- 无论采取什么样的字符编码,string 的一些方法处理一个 string 对象时是按照 bytes 来处理的,因此即使是采用 variable-length characters 的编码方式,string 在处理字符串时仍然只是会按照 bytes 处理,不会考虑一个 character 到底用了几个字节表示。
- string object 可以用 str[index] 的形式访问,每个str[index] 的类型是 char 类型。
str.substr(size_t pos = 0, size_t len = npos) const
- 从一个string obejct 中取字串作为 string
str.swap(string &x) and swap(string &x, string & y) in <algorithm>
- string::swap
- 返回值 void
- 效率没有 non-member function 中的swap 高
- <algorithm> 中的 swap
- 返回值是 void
- 参数是两个string
- <algorithm>
string 转换成 int => int a = stoi(str)
- 如果string是 “04” 可以直接转换成 4
string str = "04";
int a = stoi(str);
cout << a;
system("pause");
return 0;
document:
C string
main points:
- C-string is a character array the last element of which is the terminating zero.
strcpy and strcpy_s
- strcpy
- 有返回值,返回的是 字符串赋值的目标指针值
- strcpy_s
- strcpy 是不安全的,因为不能保证 destination 能完全 handle source 中的所有字符,有可能造成 overflow
- strcpy_s 在strcpy 的基础上添加了一个参数指明向 destination 中赋值的元素的个数,可以避免 overflow,但是可能会导致原来string object 的值被截断,不完整
- 所以只有在确保 destination 可以handle source 中的所有字符时再用这个函数
- 考虑到兼容性,用strcpy 会更好一些,此时需要在 VS 中设置 _CRT_SECURE_NO_WARNINGS
cstring (string.h)
tansform between C string and C++ string
string => char*:
- string.c_str ()
- 返回一个指向 char 数组的指针,具体的是 const char* pointer = str.c_str(), 因此不可以将 str.c_str() 的返回值赋值给 char * pointer
- 数组中包含 string object 中的所有字符,并且在最后添加一个结束符 ‘\0’,因此数组中元素的个数为 str.length() + 1
- 如果始终使用const char* pointer 来访问对应string 的每个character, 可以通过 *(pointer + n)访问所有字符,并且会和string object 的更新同同步
- 如果用 str.c_str() 一次把当前的 string 值存入了一个新开辟的数组中,那么随着string obejct 的更新,数组元素和string object 的值可能不同步
例1:
string str("elsa song hello");
// 两种处理 str.c_str() 结果的方式
char * cstr = new char[str.length() + 1];
strcpy_s(cstr,str.length()+1, str.c_str());
const char * arr = str.c_str();
for (int i = 0; i < str.length() + 1; i++)
cout << cstr[i];
cout << endl;
for (int i = 0; i < str.length() + 1; i++)
cout << *(arr + i);
cout << endl;
// 更改 str 的指定元素值
str[0] = 'w';
cout << str << endl;
for (int i = 0; i < str.length() + 1; i++)
cout << cstr[i];
cout << endl;
for (int i = 0; i < str.length() + 1; i++)
cout << *(arr + i);
cout << endl;
例2:
document: