C++ string类常用操作
  TEZNKK3IfmPf 2023年11月12日 17 0
C++


很多程序都需要处理字符串,C++string类提供了很多好用的方法。

使用需要包含头文件<string>

 

string(const char * s);          Eg:  string one("Win"); 

string(size_type n, char c);  //Eg: string two(20, '$');包含 n 个元素的字符串,每个元素都是字符c。

string(const string & str);     //Eg:string three(one)

string();                                  Eg:string four;

string(const char * s, size_type n);  Eg: string five(alls, 20); //alls是一个字符串,five获得该字符串的前20个字符。

template <class Iter>

string(Iter begin, Iter end)                Eg:  string six(alls+6, alls+10);

string(const string & str, string size_type pos=0, szie_type n = nops)   str从pos到结尾或到n个字符为止 Eg:string eight(four,7,16);

 

2.查找

size_type find(const string& str, size_type pos=0) const  从字符串pos位置开始找,返回第一次找到str的索引,没找到返回string::npos;

size_type find(const char * s, size_type pos=0, size_type n); 从pos开始找,查找s的前n个字符组成的字符串。

size_type find(char ch, size_type pos=0, size_type n)const   查找字符ch。

还有对应的 4个 rfind 返回最后一次出现的位置。


字串中的 字符 出现的位置

find_first_of()

find_last_of() 

find_first_not_of()

find_last_not_of()

 

3.比较

compare()

最常用的比较两个字符串相等   s1.compare(s2)

 

4.字符串反转

#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
int main()
{
string s = "12345";
reverse(s.begin(),s.end());
cout<< s;
system("pause");
return 0;
}

 

5.输入输出

可以用cin和cout

读取行使用:

getline(cin,str); 

getline(cin, str2,'-')       //读取直到遇到-

 

【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月12日 0

暂无评论

推荐阅读
  TEZNKK3IfmPf   19天前   26   0   0 C++
  TEZNKK3IfmPf   19天前   22   0   0 指针C++
  TEZNKK3IfmPf   2024年05月31日   23   0   0 算法C++
TEZNKK3IfmPf