1、Define
string s1 = "hello";
string s2 = "world";
string s3 = s1 + "," + s2 +"!\n";
2、append
s1 += ",shanshan\n";
3、Compare
if(s1 == s2)
.....
else if(s1 == "hello")
.....
4、 string 重载了许多操作符,包括 +, +=, <,
=,
, [], <<, >>等,正式这些操作符,对字符串操作非常方便
<string>5、find函数
<iostream>
std;
main(){
string strinfo="";
cout << strinfo ;
cin >> strinfo;
( strinfo == "" )
cout << ""<<endl;
( strinfo != "" )
cout << ""<<endl;
( strinfo < "")
cout << ""<<endl;
cout << ""<<endl;
strinfo += "";
cout << strinfo<<endl;
cout <<""<<endl;
string strtmp = "" + strinfo;
( i = 0 ; i < strtmp.size(); i ++)
cout<<strtmp[i];
0;
}
由于查找是使用最为频繁的功能之一,string 提供了非常丰富的查找函数。其列表如下:
函数名 | 描述 |
find | 查找 |
rfind | 反向查找 |
find_first_of | 查找包含子串中的任何字符,返回第一个位置 |
find_first_not_of | 查找不包含子串中的任何字符,返回第一个位置 |
find_last_of | 查找包含子串中的任何字符,返回最后一个位置 |
find_last_not_of | 查找不包含子串中的任何字符,返回最后一个位置 |
size_type find_first_of( basic_string& s, size_type pos = 0)string s(cstr) 以C-String cstr作为S的初值
size_type find_first_of( charT* s, size_type pos, size_type n)
size_type find_first_of( charT* s, size_type pos = 0)
size_type find_first_of(charT c, size_type pos = 0)
所有的查找函数都返回一个size_type类型,这个返回值一般都是所找到字符串的位置,如果没有找到,则返回string::npos。
其实string::npos表示的是-1。即没找到就返回-1。例子如下:
<string>
<iostream>
std;
main(){
string strinfo="";
string strset="";
first = strinfo.find_first_of(strset);
(first == string::npos) {
cout<<""<<endl;
-1;
}
last = strinfo.find_last_of(strset);
(last == string::npos) {
cout<<""<<endl;
-1;
}
cout << strinfo.substr(first, last - first + 1)<<endl;//string.substr是子串
0;
}
6、insert函数, replace函数和erase函数
string只是提供了按照位置和区间的replace函数,而不能用一个string字串来替换指定string中的另一个字串。
例子:
<string>
<iostream>
std;
main() {
string strinfo="";
cout<<""<<strinfo<<endl;
string_replace(strinfo, "", "");
cout<<""<<strinfo<<endl;
0;
}
string.erase(pos,srclen);//srclen是删除的长度
string.insert(pos,strdst); //pos是定位,strdst是插入的函数
string_replace(string & strBig, string & strsrc, string &strdst) {
string::size_type pos=0;
string::size_type srclen=strsrc.size();
string::size_type dstlen=strdst.size();
( (pos=strBig.find(strsrc, pos)) != string::npos){
strBig.erase(pos, srclen);
strBig.insert(pos, strdst);
pos += dstlen;
}
}
相关链接:http://www.stlchina.org/twiki/bin/view.pl/Main/STLDetailString
7、切割字符串
#include <sstream>
#include <string>
#include <iostream>
using namespace std;
int main()
{
string text = "big|dog|china|sonic|free";
stringstream ss(text);
string sub_str;
while(getline(ss,sub_str,'|')) //以|为间隔分割test的内容
cout << sub_str << endl;
return 0;
}
输出如下:
big
dog
china
sonic
free
8、构造函数和析构函数
string s 生成一个空字符串S
string s(str) Copy构造函数,生成字符串Str的一个复制品
string s(str,stridx) 将字符串Str内始于位置Stridx的部分,当作字符串S的初值
string s(str,stridx,strlen) 将字符串Str内始于位置Stridx且长度为strlen的部分,当作字符串S的初值
string s(num,c) 生成一个字符串,包含Num个C字符
string s(beg,end) 以区间[beg,end]内的字符作为s初值
s.~string() 销毁所有字符,释放内存
注意:
std::string s('x');//error
std::string s(1,'x'); //ok,create a string that has one charactor 'x'
9、substr(string.substr的方法)