C++ string 常用函数

有关字符串的操作很多,也是算法题的常见考点,本篇博客撇开算法的具体实现,来介绍一下C++的STL 中给我们提供的非常好用的函数~

赋值

将字符串2赋值给字符串1:

  1. 字符串1 = 字符串2;
  2. 字符串1.assign(字符串2);
string s1 = "I'm ";
string s2;
s2 = "1234Juruo1234";
s1.assign(s2);
cout << s1;
//输出结果:1234Juruo1234

将字符串2从第m个字符开始的n个字符赋值给字符串1:
字符串1.assign(字符串2, m, n);

string s1 = "I'm ";
string s2 = "1234Juruo1234";
s1.assign(s2, 4, 5);
cout << s1;
//输出结果:Juruo

长度

返回字符串长度:

  1. 字符串1.length();
  2. 字符串1.size();
string s1 = "1234Juruo1234";
cout << s1.length() << endl;
cout << s1.size() <<endl;
/*
输出结果:
13
13
*/

比较

“>”, “<”, “==”, “>=”, "<="均可以用于字符串比较。

string PPAP[] = {"I", "have", "a", "pen", "an", "apple", "um", "apple-pen"};
sort(PPAP, PPAP + 8);
for(int i = 0; i < 8; i++){
    cout << PPAP[i] << endl;
}
/*
输出结果:
I
a
an
apple
apple-pen
have
pen
um
*/

查找

在字符串1中从第m个字符开始查找字符串2,返回第一次出现的首字母位置,失败时返回-1:
字符串1.find(字符串2, m);

string s1 = "ggabcdabcgggabcdefg";
string s2 = "gg";
int pos = -1;
while(1){
    pos = s1.find(s2, pos+1);
    if(pos == -1) break;
    cout << pos << ' ';
}
//输出结果:0 9 10 

在字符串1中从第m个字符开始从后向前查找字符串2,返回第一次出现的首字母位置,失败时返回-1:
字符串1.rfind(字符串2, m);

string s1 = "ggabcdabcgggabcdefg";
string s2 = "gg";
int pos = s1.length();
while(pos > 0){
    pos = s1.rfind(s2, pos-1);
    if(pos < 0) break;
    cout << pos << ' ';
}
//输出结果:10 9 0;

连接

将字符串2接到字符串1尾部:

  1. 字符串1.append(字符串2); //字符不可
  2. 字符串1 += 字符串2; //字符亦可
string s1 = "I'm ";
string s2 = "Juruo";
s1.append(s2);
// 或 s1 += s2;
cout << s1;
//输出结果:I'm Juruo

将字符串2从第m个字符开始的n个字符接到字符串1尾部:
字符串1.append(字符串2, m, n);

string s1 = "I'm ";
string s2 = "1234Juruo1234";
s1.append(s2, 4, 5);
cout << s1;
//输出结果:I'm Juruo

交换

字符串1.swap(字符串2);

string s1 = "I'm ";
string s2 = "Juruo";
s1.swap(s2);
cout << s1 << endl;
//输出结果:Juruo

子串

返回字符串1从第m个字符开始的n个字符所组成的子串:
字符串1.substr(m, n);

string s1 = "I'm ";
string s2 = "1234Juruo1234";
s1 = s2.substr(4, 5);
cout << s1 << endl;
//输出结果:Juruo

替换

在字符串1中删除从m开始的n个字符,然后在m处插入串s2
字符串1.replace(m, n, s2);

string s1 = "I'm Juruo";
string s2 = "Juruo";
string s3 = "Dalao";
int pos = s1.find(s2);
s1.replace(pos, s2.length(), s3);
cout << s1;
//输出结果:I'm Dalao

插入

在字符串1的第m个字符处插入字符串2:
字符串1.insert(m, 字符串2);

string s1 = "I'm Juruo";
string s2 = "not ";
s1.insert(s1.find("Juruo", 0), s2 );
cout << s1 << endl;
//输出结果:I'm not Juruo

删除

从字符串1的第m个字符开始,删除n个字符:
字符串1.erase(m, n);

string s1 = "I'm not Dalao";
s1.erase(s1.find("not"), 4);
cout << s1 << endl;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值