string类的常用函数(总结)

string类的常用函数(总结)

string类常用成员函数

(1)求长度

int length(); int size(); //求长度

(2)比较2个字符串 strcmp(s1,s2) == 0

直接用运算符 < > = = != <= >=

(3)字符串复制 strcpy(s1,s2); s2->s1

可直接用运算符 =

(4)字符串连接 strcat(s1,s2); s1 + s2 -> s1

直接用运算符 + 进行连接

(5)空串判断

bool empty(); //判断是否为空串

(6)子串 substr();//求字串(重点)

string substr(int pos = 0,int n = npos) const;//返回pos开始的n个字符组成的字符串

int main (){

string s = "hello, world!";

string ss1 = s.substr(2); //llo, world!

string ss2 = s.substr(2,3); //llo

cout << ss1 << endl << ss2 << endl;

}

(7)erase();//删除若干个字符(重点)

string &erase(int pos = 0, int n = npos);//删除pos开始的n个字符,返回修改后的字符串,源字符串也被修改

注意:::原来的s也会改变;

int main (){

string s = "hello,world!";

string ss1 = s.erase(6); //删除下标为6的字符开始的所有字符,hello,

string ss2 = s.erase(1,2); //删除下标为2的字符开始的2个字符,删除el

cout << s << endl << ss1 << endl << ss2 << endl;

}

(8)insert();//插入字符

string s=",";

s.insert(0,"heo"); cout<

s.insert(4,"world",2); cout<

s.insert(2,2,'l');cout<

s.insert(s.end(),'r');cout<

s += "ld!";cout<

注意:::是在下标为i前面加;

(9)replace();//替换字符(重点)

用法一:用str替换指定字符串从起始位置pos开始长度为len的字符

string& replace (size_t pos, size_t len, const string& str);

#include

#include

using namespace std;

int main()

{

string str = "abcdefghigk";

str=str.replace(str.find("c"),2,"#"); //从第一个a位置开始的两个字符替换成#

cout<

return 0;

}

用法二: 用substr的指定子串(给定起始位置和长度)替换从指定位置上的字符串

string& replace (size_t pos, size_t len, const string& str, size_t subpos, size_t sublen);

#include

#include

using namespace std;

int main()

{

string str = "he is@ a@ good boy";

string substr = "12345";

str=str.replace(0,5,substr,substr.find("1"),4); //用substr的指定字符串替换str指定字符串

cout << str << endl;

return 0;

}

(10)find系列函数;//查找字串

C++中string的find()函数的用法(列题见F - All in All UVA - 10340 )

string的find()函数用于找出字母在字符串中的位置。

s.find(str,position)

find()的两个参数:

str:是要找的元素

position:字符串中的某个位置,表示从从这个位置开始的字符串中找指定元素。

可以不填第二个参数,默认从字符串的开头进行查找。

返回值为目标字符的位置,当没有找到目标字符时返回string::npos。(或-1)

数组的find(pos,pos+n,x)用法与string的不同

#include

#include

using namespace std;

typedef long long ll;

int main(){

int a[10]={1,2,3,4,5,6};

string s="abcdefg";

cout << find(a,a+10,3)-a << endl;

cout << s.find('e') << endl;

cout << s.find("bcd") << endl;

cout << s.find('e',4) << endl;//从下标为4开始搜索,输出-1;

return 0;

}

reverse()函数的使用

#include

#include

using namespace std;

typedef long long ll;

int main(){

char a[8]={"abcdefg"};

string s="abcdefg";

cout << "string reverse用法:reverse(s.begin(),s.end());" << endl;

reverse(s.begin(),s.end());

cout << s << endl;

cout << "字符串数组 reverse用法:reverse(a,a+10);" << endl;

reverse(a,a+7);

for(int i=0;i<7;i++){

cout << a[i];

}

return 0;

}

string 的STL中sort使用

sort(s.begin(),s.end());

相关推荐

法国身价10.66亿欧略逊巴西11.37亿欧 姆巴佩NO.1 365体育是正规的吗

法国身价10.66亿欧略逊巴西11.37亿欧 姆巴佩NO.1

📅 07-13 👁️ 2476
长安unit参数配置表 beat365登录平台

长安unit参数配置表

📅 07-05 👁️ 4098