c++ string类常见操作

1.反转字符串

反转字符串为常见的日常操作,在c++中可以用algorithm里的reverse方法进行操作。

#include<iostream>
#include<vector>
#include<cctype>
#include<string>
using namespace std;

void func0() {
    string s = "abcde";
    std::reverse(s.begin(), s.end());
    cout<<"s is: "<<s<<endl;

    string s1 = "abcde";
    string s2(s1);
    std::reverse(s2.begin(), s2.end());
    cout<<"s1 is: "<<s1<<endl;
    cout<<"s2 is: "<<s2<<endl;
}

上述方法输出为

s is: edcba
s1 is: abcde
s2 is: edcba

使用reverse方法以后,字符串本身发生了改变。如果需要保留原有字符串,则可以再新创建一个字符串进行反转。

2.插入字符

插入字符可以使用push_back与insert方法。其中,push_back是在字符串尾部操作,而insert可以在字符串任意位置进行操作。

void func1() {
    string s = "abcde";
    s.push_back('f');
    s.insert(s.begin(), '0');
    cout<<"s is: "<<s<<endl;
}
s is: 0abcdef

3.字符串拼接

append方法可以用来进行字符串拼接,”+“也可以收到同样效果

void func2() {
    string s = "aaa";
    s.append("bbb");
    cout<<"s is: "<<s<<endl;

    string ss = "aaa";
    ss += "bcd";
    cout<<"ss is: "<<ss<<endl;
}
s is: aaabbb
ss is: aaabcd

4.字符串遍历

遍历可以使用下标,也可以使用迭代器。迭代器可以是正向,也可以是反向。

void func3() {
    string s = "abcd";
    for(int i=0; i<s.size(); i++) {
        cout<<s[i]<<" ";
    }
    cout<<endl;

    for(auto iter=s.begin(); iter<s.end(); iter++) {
        cout<<*iter<<" ";
    }
    cout<<endl;

    for(auto riter=s.rbegin(); riter<s.rend(); riter++) {
        cout<<*riter<<" ";
    }
    cout<<endl;
}
a b c d 
a b c d 
d c b a 

5.删除字符串中的字符

void func4() {
    string s = "abcdefghigk";
    s.erase(s.begin());
    cout<<s<<endl;
    s.erase(0, 3);
    cout<<s<<end
bcdefghigk
efghigk

从上面的例子可以看出,erase方法中的参数,可以使用迭代器,也可以指定索引位置。

6.字符串替换

void func5() {
    string s = "ni hao hello world";
    s.replace(0, 2, "ta");
    cout<<s<<endl;
}
ta hao hello world

7.删除所有空格

void func6() {
    string str = "ni hao  aaa";
    str.erase(std::remove(str.begin(), str.end(), ' '), str.end());
    cout<<str<<endl;
    cout<<str.size()<<endl;
}
nihaoaaa
8

注意remove方法与erase方法配合使用。

8.转大小写

void func7() {
    string s = "abcd";
    for(int i=0; i<s.size(); i++) s[i] = toupper(s[i]);   
    cout<<"s is: "<<s<<endl;

    transform(s.begin(), s.end(), s.begin(), ::tolower);
    cout<<"s is: "<<s<<endl;
}
s is: ABCD
s is: abcd

9.判断子串起始位置

void func8() {
    string s = "abcdefg";
    int index1 = s.find("abc");
    cout<<"index1 is: "<<index1<<endl;

    int index2 = s.find("abd");
    cout<<"index2 is: "<<index2<<endl;
}
index1 is: 0
index2 is: -1

find方法如果找到子串,返回起始位置。如果没有找到,则返回-1.

10 获取子串

void func9() {
    string s = "abcdefg";
    cout<<s.substr(0, 3)<<endl;
}
abc

注意substr方法,得到的结果为左闭右开区间。

  • 2
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值