//The string class is an instantiation of the basic_string class template, defined in <string> as: typedef basic_string<char> string; string实际上是basic_string<char>的一个typedef,同时省略了与内存管理相关的参数。
string word; 程序将从标准输入读取一组 string 对象,然后在标准输出上逐行输出: while (cin >> word) cout << word << endl;
上例中,用输入操作符来读取 string 对象。该操作符返回所读的istream 对象,并在读取结束后,作为 while 的判断条件。如果输入流是有效的,即还未到达文件尾且未遇到无效输入,则执行 while 循环体,并将读取到的字符串输出到标准输出。如果到达了文件尾,则跳出 while 循环。
使用getline 读取整行文本
1 2 3
string line; // read line at time until end-of-file while (getline(cin, line)) //循环读取输入流 cout << line << endl;
赋值
1 2 3 4
// st1 is an empty string, st2 is a copy of the literal string st1, st2 = "The expense of spirit"; st1 = st2; // replace st1 by a copy of st2 它必须先把 st1 占用的相关内存释放掉,然后再分配给 st2 足够存放 st2 副本的内存空间,最后把 st2 中的所有字符复制到新分配的内存空间。
s.append(args); 将args追加到s.返回一个指向s的引用. s.assign(args); 将s中的字符替换为args指定的字符.返回一个指向s的引用. s.push_back(char c); 在末尾添加一个元素,返回值为空 string& insert( size_t pos1, size_t n, char c ); 在字符串pos1位置,插入n次c字符。 size_tcopy( char* s, size_t n, size_t pos = 0)const; 从pos位置开始,复制n个字符到s指针指向的内存;
insert
1 2 3 4 5 6 7 8 9 10 11 12 13 14
string str="to be question"; string str2="the "; string str3="or not to be"; string::iterator it; // used in the same order as described above: str.insert(6,str2); // to be (the )question str.insert(6,str3,3,4); // to be (not )the question str.insert(10,"that is cool",8); // to be not (that is )the question str.insert(10,"to be "); // to be not (to be )that is the question str.insert(15,1,':'); // to be not to be(:) that is the question it = str.insert(str.begin()+5,','); // to be(,) not to be: that is the question str.insert (str.end(),3,'.'); // to be, not to be: that is the question(...) str.insert (it+2,str3.begin(),str3.begin()+3); // (or ) Output:to be, ornot to be: that is the question...
append()
1 2 3 4 5 6 7 8 9 10 11 12
string str; string str2="Writing "; string str3="print 10 and then 5 more";
str.append(str2); // "Writing " str.append(str3,6,3); // "10 " str.append("dots are cool",5); // "dots " str.append("here: "); // "here: " str.append(10,'.'); // ".........." str.append(str3.begin()+8,str3.end()); // " and then 5 more" str.append<int>(5,0x2E); // "....." Output: Writing 10 dots here: .......... and then 5 more.....