STL-string

Posted on 2015-07-21 00:33  指尖敲击流逝的岁月  阅读(179)  评论(0)    收藏  举报

1.字符串查找
str.find()
str.rfind()
str.find_first_of()
str.find_last_of()

代码区:
  1. string str1 = "hello, this is just a test!";
  2. string str2 = "st";
  3. string str3 = "west";
  4. int pos = 0;
  5. cout <<str1<<endl;
  6. cout <<"length is "<<str1.size()<<endl;//27
  7. //正向查找完全匹配(所要被查找的字符)
  8. pos = str1.find(str2);
  9. cout <<"st the first place is at "<<pos<<endl; //st in just, 17
  10. pos = str1.find(str3);
  11. cout <<"west the first place is at "<<pos<<endl;//can not find
  12. //反向查找完全匹配(所要被查找的字符)
  13. pos = str1.rfind(str2);
  14. cout <<"west the last place is at "<<pos<<endl;//st in test,24
  15. //正向查到第一次出现的字符(可以理解为要被查找的字符,分割成最小单位,一遍遍遍历,这里是先遍历w,没有在遍历e。。。)
  16. pos = str1.find_first_of(str3);
  17. cout <<"west the place from first is at "<<pos<<endl;//e in hello, 1
  18. //反向查到第一次出现的字符(可以理解为要被查找的字符,分割成最小单位,一遍遍遍历,这里是先遍历w,没有在遍历e。。。)
  19. pos = str1.find_last_of(str3);
  20. 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).
 
代码区:
  1. string str,strout;
  2. cin>>str;
  3. strout = str.substr(0,3);//不检查范围
  4. cout <<strout<<endl;



3.字符串赋值
str.assign()

  1. int main()
  2. {
  3. string str1 = "This is a test ! ";
  4. string str2;
  5. /*
  6. 赋值
  7. Copies str
  8. string& assign (const string& str)
  9. */
  10. str2.assign(str1);
  11. cout << str2<<endl;
  12. /*
  13. 截取子串
  14. 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).
  15. string& assign (const string& str, size_t subpos, size_t sublen = npos); --C++14
  16. */
  17. str2.assign(str1,5,11); // start by 5,len is 11
  18. cout << str2 <<endl;
  19. /*
  20. 填充N个相同的值
  21. Replaces the current value by n consecutive copies of character c.
  22. string& assign (size_t n, char c);
  23. */
  24. str2.assign(15,'@');
  25. cout <<str2<<endl;
  26. return 0;
  27. }