1.为什么要选择string类
内存不受限,有没有在OJ为了输入数据的字符串的长度不可知而痛苦万分,有了string类,所有都交给他来帮你完成吧,暂时也就可以忽略内存管理这件**的事情了。
丰富的操作符,这一点有点类似与Python这样的脚本语言的中的str,用起来比较的得心应手,要是再有个分割split()函数,去除头尾的空字符函数strip(),然后vector再来个join函数用起来感觉应该是大大的好。
所以既然选择了C++,就应该好好把string 当成基本类型来使用。
2.怎么用string类
2.1 构造函数
#include <iostream>
#include <string>
int main ()
{
std::string s0 ("Initial string");
// constructors used in the same order as described above:
std::string s1; // null
std::string s2 (s0); //copy constructor
std::string s3 (s0, 8, 3); // starts at the 8th ends 6th
std::string s4 ("A character sequence", 6); //the first 6th
std::string s5 ("Another character sequence");
std::string s6 (10, 'x');
std::string s7a (10, 42); // 42 is the ASCII code for '*'
std::string s7b (s0.begin(), s0.begin()+7);
std::cout << "s1: " << s1 << "\ns2: " << s2 << "\ns3: " << s3;
std::cout << "\ns4: " << s4 << "\ns5: " << s5 << "\ns6: " << s6;
std::cout << "\ns7a: " << s7a << "\ns7b: " << s7b << '\n';
return 0;
}
结果
s1:s2: Initial string
s3: str
s4: A char
s5: Another character sequence
s6: xxxxxxxxxx
s7a: **********
s7b: Initial
2.2 使用
迭代器:std::string::iterator it ;
for(it = s.begin();it != s.end(); it++)
sdt::cout<<*it;//print the single character
操作符[]: 这个比较像c里面字符串的操作
int length = s.length();
for(int i=0; i < length; i++)
std::cout<<s[i];
区别点:
c语言里面识别一个字符串的结束符为'\0',
但是string类里面不是的,所以要把字符串截短一定要用erase()函数把不要的字符串拿掉,,不能加上‘\0 ’就可以了
例子:
#include <string> #include <stdio.h> #include <cstring> int main () { std::string s("Initial string"); // constructors used in the same order as described above: int l = s.length(); s[l/2] = '\0'; printf("Initial length %d \npresent length %d \nctring length%d\n", l, s.length(),strlen(s.c_str())); if (s[l] == '\0') { printf("s ends with \'\\0\'\n"); } return 0; }
结果:
Initial length 14
present length 14ctring length7s ends with '\0'
3,操作函数
赋值 =
附加 + +=
compare()
std::string str1 ("green apple"); std::string str2 ("red apple"); if (str1.compare(str2) != 0) std::cout << str1 << " is not " << str2 << '\n'; if (str1.compare(6,5,"apple") == 0) std::cout << "still, " << str1 << " is an apple\n"; if (str2.compare(str2.size()-5,5,"apple") == 0) std::cout << "and " << str2 << " is also an apple\n"; if (str1.compare(6,5,str2,4,5) == 0) std::cout << "therefore, both are apples\n"; return 0;
4,查找
找不到的返回值为: std::string::npos
5,其他split参考:http://www.cplusplus.com/faq/sequences/strings/split/
6,如果需要转换成char* 就用c_str()
参考:http://www.cplusplus.com/reference/string/string/