string类包含了大量的方法接口用于操作字符串。string头文件和string.h、cstring两种头文件没有关系,后两种是用于兼容C风格的字符串函数的库,不支持string类。
初始化
构造
#include <iostream> #include <string> using namespace std; int main() { string one("ingy win!"); cout<<one<<endl; string two(20, '$'); cout<<two<<endl; string three(one); cout<<three<<endl; one += "opp!"; cout<<one<<endl; two="ing test "; three[0]='P'; string four; four=two+three; cout<<four<<endl; char alls[]="all ingy test code!"; string five(alls, 20); cout<<five<<"! "; string six(alls+6, alls+10); cout<<six<<", "; string seven(&five[6], &five[10]); cout<<seven<<"... "; string eight(four, 7, 16); cout<<eight<<" in motion!"<<endl; return 0; }
I/O
对于C风格字符串,有三种输入方式方式,而string类有两种
char val[100]; cin >> val; //输入一个字符串,如果输入超过100个字符,则会发生错误 cin.getline(val, 100); //输入一行,需要指明输入的字符数 cin.get(val, 100); //输入,需要指明输入的字符数 string str; cin >> str; //输入一个字符串,自动调整大小,所以可以无限输入字符 getline(cin, str); //输入一行,无需指明字符数,可以自由输入
#include <iostream> #include <string> #include <cstdlib> #include <fstream> using namespace std; int main() { ifstream fin; fin.open("test.txt"); if(!fin.is_open()) { cout << "can't open file. Bye. "; exit(1); } string item; int count = 0; getline(fin, item, ':'); while(fin) { ++count; cout << count <<": "<< item <<endl; getline(fin, item, ':'); } cout << "Done "; fin.close(); return 0; }
使用
字符串种类