c++去除string首尾空格、string转int、int转string、char换string

去除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;
    }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值