1.字符串查找
str.find()
str.rfind()
str.find_first_of()
str.find_last_of()
代码区:
string str1 = "hello, this is just a test!";string str2 = "st";string str3 = "west";int pos = 0;cout <<str1<<endl;cout <<"length is "<<str1.size()<<endl;//27//正向查找完全匹配(所要被查找的字符)pos = str1.find(str2);cout <<"st the first place is at "<<pos<<endl; //st in just, 17pos = str1.find(str3);cout <<"west the first place is at "<<pos<<endl;//can not find//反向查找完全匹配(所要被查找的字符)pos = str1.rfind(str2);cout <<"west the last place is at "<<pos<<endl;//st in test,24//正向查到第一次出现的字符(可以理解为要被查找的字符,分割成最小单位,一遍遍遍历,这里是先遍历w,没有在遍历e。。。)pos = str1.find_first_of(str3);cout <<"west the place from first is at "<<pos<<endl;//e in hello, 1//反向查到第一次出现的字符(可以理解为要被查找的字符,分割成最小单位,一遍遍遍历,这里是先遍历w,没有在遍历e。。。)pos = str1.find_last_of(str3);cout <<"west the place from last is at "<<pos<<endl;// t in test,25

2.字符串截取
str.substr(a,b) //左闭右开
string substr (size_t pos = 0, size_t len = npos) const;
Generate substring
Returns a newly constructed string object with its value initialized to a copy of a substring of this object.
The substring is the portion of the object that starts at character position pos and spans len characters (or until the end of the string, whichever comes first).
代码区:
string str,strout;cin>>str;strout = str.substr(0,3);//不检查范围cout <<strout<<endl;

3.字符串赋值
str.assign()
int main(){string str1 = "This is a test ! ";string str2;/*赋值Copies strstring& assign (const string& str)*/str2.assign(str1);cout << str2<<endl;/*截取子串Copies the portion of str that begins at the character position subpos and spans sublen characters (or until the end of str, if either str is too short or if sublen is string::npos).string& assign (const string& str, size_t subpos, size_t sublen = npos); --C++14*/str2.assign(str1,5,11); // start by 5,len is 11cout << str2 <<endl;/*填充N个相同的值Replaces the current value by n consecutive copies of character c.string& assign (size_t n, char c);*/str2.assign(15,'@');cout <<str2<<endl;return 0;}

浙公网安备 33010602011771号