(8)size,length:计算字符串长度
这里的计算字符串长度和C语言中不同,是不包括末尾的的,计算的是真实的长度。
// size(), length():计算字符串长度
string stringCount = "chenyufeng";
cout << "stringSize = " << stringCount.size() << endl;
cout << "stringLength = " << stringCount.length() << endl;
上述的打印结果都是10.
(9)empty:判断字符串是否为空
// empty():判断字符串是否为空 string stringIsEmpty = ""; string stringNotEmpty = "chen"; if (stringIsEmpty.empty()) { cout << "stringIsEmpty == empty" << endl; } else { cout << "stringIsEmpty != empty" << endl; } if (stringNotEmpty.empty()) { cout << "stringNotEmpty == empty" << endl; } else { cout << "stringNotEmpty != empty" << endl; } |
(10)字符串的输入输出流
// 输入输出stream
cout << "请输入一个字符串"<<endl;
string stringInput;
cin >> stringInput;
cout << "stringInput = " << stringInput << endl;
字符串也可以类似于C++其他数据类型一样使用输入输出流。可以使用回车键结束输入流。
(11)max_size:字符串的最大可容纳量。
// max_size:
string stringMaxSize;
cout << "stringMaxSize = " << stringMaxSize.max_size() << endl;
打印结果为:18446744073709551599 。表示该字符串可以容纳这么多的字符数。
(12)[], at :元素存取与修改
// [],at() :元素存取
string stringAt = "chenyufeng";
cout << "stringAt[3] = " <<stringAt[3] << endl;
cout << "stringAt.at(3) = " << stringAt.at(3) << endl;
stringAt[3] = '6';
stringAt.at(5) = '9';
cout << "stringAt = " << stringAt << endl;
字符串可以和数组一样进行操作,使用下标进行存取,并可以进行修改原字符串。
(13)compare:字符串的比较,返回0,1 ,-1。
// compare()
string stringCompare = "chenyufeng";
int aaa = stringCompare.compare("chen"); // > 0
int bbb = stringCompare.compare("chenyufeng"); // == 0
int ccc = stringCompare.compare("done"); // < 0
cout << "aaa = " << aaa << ";bbb = " << bbb << ";ccc = " << ccc << endl;
(14)substr:取子字符串
// substr
string stringSubstr = "chenyufeng";
// 从索引为4开始的3个字符
cout << "stringSubstr.substr(4,3) = " << stringSubstr.substr(4,3) << endl;
// 从索引为4开始的所有字符
cout << "stringSubstr.substr(4) = " <<stringSubstr.substr(4) << endl;
// 整个字符
cout << "stringSubstr.substr() = " <<stringSubstr.substr() << endl;
(15)find:查找某个字符
// find
string stringFind = "chenyufeng";
stringFind.find('n');
cout << "stringFind.find('n') = " << stringFind.find('n') << endl;
cout << "stringFind.find_first_of('e') = " << stringFind.find_first_of('e') << endl;
cout << "stringFind.find_last_of('e') = " << stringFind.find_last_of('e') << endl;
默认find函数是返回某个字符第一次出现的下标index。find_first_of和find_last_of则分别是第一次和最后一次出现某个字符的index。
上述15个C++中的字符串处理函数是最为常见的,当然其他还有不少,我会在在后续的使用中继续补充。string其实也是STL中的一部分。