c++string函数总结

总结一些string函数:

insert():

string a="qwe";
string b="asd";
a.insert(2,b);
cout<<a;

输出:qwasde

erase():

string a="qwe";
a.erase(0,1);//删除第一个字符
cout<<a;

结果:we

replace():

string a="qwe";
a.replace(2,3,"dfg");//将a的第2个位置后的三个字符替换为dfg,没有的补上
cout<<a;

输出:qwdfg

find()和rfind();

string a="qwereet";
int b = a.find('e');//字符也可以,返回找到第一个字符的位置,若找不到,返回-1,也就是string::npos
int c = a.find("re");
cout<<b<<" "<<c;

输出:2 3

rfind():到着找

string a="qwwreet";
int b = a.rfind('e');
int c = a.rfind("re");//第一个r的位置在倒数第三个
cout<<b<<" "<<c;

输出:5 3

find_first_of()与find_last_of():

//将字符串中所有的元音字母换成*
//代码来自C++ Reference,地址:http://www.cplusplus.com/reference/string/basic_string/find_first_of/
#include<iostream>
#include<string>

using namespace std;

int main()
{
    std::string str("PLease, replace the vowels in this sentence by asterisks.");
    std::string::size_type found = str.find_first_of("aeiou");
    while (found != std::string::npos)
    {
        str[found] = '*';
        found = str.find_first_of("aeiou", found + 1);
    }
    std::cout << str << '\n';
    return 0;
}
//运行结果:
//PL**s* r*pl*c* th* v*w*ls *n th*s s*nt*nc* by *st*r*sks

find_last_of 倒着找

find_first_not_of()与find_last_not_of():

感觉和前面一类的相反的,类似于找了个补集。即在a中搜寻b中没有的字符并返回位置

#include<bits/stdc++.h>
using namespace std;

int main(){
    string str("PLease, replace the vowels in this sentence by asterisks.");
    int found = str.find_first_not_of("aeiou");
    while (found != -1){
        str[found] = '*';
        found = str.find_first_not_of("aeiou", found + 1);
    }
    cout << str;
    return 0;
}

输出:**ea*e***e**a*e***e**o*e***i****i***e**e**e****a**e*i****

string转int:

#include<bits/stdc++.h>
using namespace std;

int main(){
    string a="123";
    int c = atoi(a.c_str());//atoi传入的参数必须是char*,所以c_str返回一个char * char类型的指针
    cout<<c;
    return 0;
}
输出:123

猜你喜欢

转载自blog.csdn.net/Endeavor_G/article/details/84306003
今日推荐