cpp<br />#include <cstring><br />#include <string><br />
cpp<br />string a;//声明String a<br />a="12345";//赋值<br />string b="54321";<br />int len=a.length();//获取长度<br />cin >> a;//输入(以空格换行符为界限)<br />getline(cin,a)//可以读入空格<br />cout << a;<br />swap(a,b)//交换<br />printf("%s\n",a.c_str());//C风格输出,c_str()是啥?<br />
cpp<br />string c=a+b;<br />c="123"+c+"321";<br />> < == != : 根据字典序比较<br />inline bool cmp(string a,string b){return a>b;}<br />...<br />int main()<br />{<br /> sort(a+1,a+1+n,cmp);<br />}<br />
cpp<br />string str="to be question";<br />string str2="the ";<br />str.insert(6,str2);// to be (the )question<br />
cpp<br />str.erase(0,3); //(~~to ~~)be question<br />
cpp<br />str.replace(0,2,"To");// (To) be question<br />
cpp<br />string str="To be, or not to be - that is the question";<br />int t=str.find("be");\\ t=3,str[t]='b'(To be 的be)<br />int t=str.find("be",4);\\ t=17,str[t]='b'(not to be的be)<br />
cpp<br />int t=str.rfind("be");\\ t=17,str[t]='b'(not to be的be)<br />int t=str.rfind("be",16);\\ t=3,str[t]='b'(To be 的be)<br />
cpp<br />if (str.find("Be")==string::npos)<br />{<br /> cout <<"NO"<<endl;// 输出NO<br />}<br />if (str.rfind("Be")==-1)<br />{<br /> cout <<"NO"<<endl; // 输出NO<br />}<br />
cpp<br />#include<iostream><br />#include<string><br /><br />using namespace std;<br /><br />int main()<br />{<br /> std::string str("PLease, replace the vowels in this sentence by asterisks.");<br /> std::string::size_type found = str.find_first_of("aeiou");<br /> while (found != std::string::npos)<br /> {<br /> str[found] = '*';<br /> found = str.find_first_of("aeiou", found + 1);<br /> }<br /> std::cout << str << '\n';<br /> return 0;<br />}<br />//运行结果:<br />//PL**s* r*pl*c* th* v*w*ls *n th*s s*nt*nc* by *st*r*sks<br />
cpp<br />string str="To be, or not to be - that is the question";<br />str.substr(0,2);// To<br />str.substr(str.find("question"));// question<br />
cpp<br />ostringstream outs; //输出字符串流<br />int x = 12; <br />outs << x; //向输出字符串流中输出x的内容 <br />string a=outs.str(); //利用字符串流的str函数获取流中的内容<br />
cpp<br />string a="12";<br />istringstream ins(a); //输入字符串流,流的内容初始化为a<br />int x; <br />ins >> x; //从is流中读入并存入x中<br />(没有用的东西。。)<br />
cpp<br />string str = "hello";<br />const char* p = str.data();//加const 或者用char * p=(char*)str.data();的形式<br />
cpp<br />string str=“world”;<br />const char *p = str.c_str();//同上,要加const或者等号右边用char*<br />
cpp<br />string str="hmmm";<br />char p[50];<br />str.copy(p, 5, 0);//这里5代表复制几个字符,0代表复制的位置,<br />*(p+5)=‘\0’;//注意手动加结束符!!!<br />
cpp<br />string pp = "dagah";<br />char p[8];<br />int i;<br />for( i=0;i<pp.length();i++)<br /> p[i] = pp[i];<br />p[i] = '\0';<br />