0
点赞
收藏
分享

微信扫一扫

C++ string类常用操作


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

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

 

1.构造字符串

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,'-')       //读取直到遇到-

 

举报

相关推荐

0 条评论