string的常用操作

记录一下平时用到的string操作:

1.int转为string

方法一:to_string()

c++11标准增加了全局函数std::to_string:

string to_string (int val);

string to_string (long val);

string to_string (long long val);

string to_string (unsigned val);

string to_string (unsigned long val);

string to_string (unsigned long long val);

string to_string (float val);

string to_string (double val);

string to_string (long double val);

例子:

string pi = "pi is " + to_string(3.14); 
cout << pi << endl;    //输出pi is 3.140000

方法二:借助stringstream(慢)

#include <sstream> //stringstream
#include <string> //string
#include <iostream>
using namespace std;
 
int main(){
    int n=100;
    stringstream ss ;
    string str;
    
    ss << n;
    str = ss.str();    
    cout << str;    //输出100
 
    return 0;
}

2.string转int

方法一:str.c_str()

string str = "1234";
int n = atoi(str.c_str());    
cout << "n=" << n;    //输出n=1234

方法二:借助stringstream

#include <sstream>
istringstream is("1234"); //构造输入字符串流,流的内容初始化为“1234”的字符串   
int i;   
is >> i; //从is流中读入一个int整数存入i中    
cout << i;    //输出1234

 方法三:使用stoi()

#include <string>
string str = "1234";
int n = stoi(str);    
cout << "n=" << n;    //输出n=1234

 

(参考:https://www.cnblogs.com/smile233/p/8379802.html)

3.字符串拼接 +,append()

string str = "12345";
str += "abc";
str.append("def");
cout << str << endl;        //输出12345abcdef
str.append("Myinput",3);    //只取myinput前3个字符
cout << str << endl;        //输出12345abcdefMyi

string tmp;
tmp.append(str, 2, 2);        //从下标为2开始取2个元素
cout << tmp << endl;        //输出34

4.修改某个元素的值 [],at()

string str = "12345";
str[2] = 'a';
cout << str << endl;    //输出12a45
string str = "12345";
str.at(2) = 'a';
cout << str << endl;    //输出12a45
at(n)返回下表为n的元素的引用:
char& at (size_t pos); const char& at (size_t pos) const;

5.子串截取 substr()

string str = "12345";
string tmp = str.substr(1, 10);    //从下标1开始截取10个字符,实际会截取到字符串末尾
cout << tmp << endl;    //输出2345

6.查找和替换 find(),replace()

string str = "12ab55ab";
int a = str.find("ab");    //返回第一次找到的子串下标,否则-1
cout << a << endl;        //输出2
a = str.find("ab", 3);    //从下标为3开始找
cout << a << endl;        //输出6    

a = str.rfind("ab");    //从右边开始
cout << a << endl;        //输出6    
string str = "12345";
str.replace(2, 2, "qqqqq");    //从下标为2开始,用qqqqq替换2个元素
cout << str << endl;    //输出12qqqqq5

7.插入和删除 insert(),erase()

string str = "12345";
str.insert(5, "aa");    //在下标为5的前面插入aa,这里n不能超过字符串长度,否则会越界
cout << str << endl;    //输出12345aa
string str = "12345";
str.erase(2, 10);        //从下标为2的元素开始,删除10个元素,这里实际是到末尾
cout << str << endl;    //输出12

8.翻转 reverse()

string str = "12345";
reverse(str.begin(), str.end());
cout<<str;    //输出54321

9.比较 compare()

string str = "12345";
string str2 = "12345";
cout << str.compare(str2) << endl;    //大于=>1,等于=>0,小鱼=>-1,这里输出0

(参考:https://www.cnblogs.com/xiximayou/p/12111059.html)

 

posted @ 2020-04-28 10:52  Brickert  Views(233)  Comments(0Edit  收藏  举报