去除string首尾空格,利用string中函数
s.erase();
s.find_first_not_of()
s.find_last_not_of()
#include <bits/stdc++.h>
using namespace std;
void trim(string &s){
if(s.empty())
return;
s.erase(0,s.find_first_not_of(' '));//去除首部全部空格
s.erase(s.find_last_not_of(' ')+1);//去除尾部全部空格
}
int main(){
string s=" abc def ghi kl m ";
cout<<s<<"结束"<<endl;
trim(s);
cout<<s<<"结束"<<endl;
return 0;
}
abc def ghi kl m 结束
abc def ghi kl m结束
string 与 int 之间的转换
int 转成 string
string str;
int a=23233;
str=to_string(a);
string 转成 int
string str="2334412";
int a;
a=stoi(s);
//或者
a=atoi(s.c_str());
区别是stoi的形参是const string*,而atoi的形参是const char*。c_str()的作用是将const string* 转化为const char*
如果将字符串string str
中每一个字符str[i]
转换为一个vector<string> strcopy
数组中strcopy[i]
,直接利用strcopy.push_back(str[i])
,会出错
以下出错!!!!
string str="qwesdafcxz";
vector<string> strcopy;
for(int i=0;i<str.size();i++){
strcopy.push_back(str[i]);
}
正确的是先转换str[i]
为string ,再放进去
string str="qwesdafcxz";
vector<string> vec;
for(int i=0;i<str.size();i++){
string tmp;
tmp+=str[i];
vec.push_back(tmp);
}
char转string
利用+=操作符
string s1="abcdefghijk";
string s3;
for(auto x:s1){
s3=s3+x;
}
利用push_back
string s1="abcdefghijk";
string s4;
for (auto x:s1) {
s4.push_back(x);
}
利用stringstream
string s1="abcdefghijk";
string s5;
for(auto x:s1){
stringstream ss;
ss<<x;
string tmp;
ss>>tmp;
s5=s5+tmp;
}