string基本操作(C++)


  1. 1.1 “+”
    str = str + ss;
    cout << str << endl; //234561
  1. 提取字串
    2.1 substr
    substr(pos): 提取从位置pos开始到末尾的子串。
#include <iostream>
#include <string>
using namespace std;

int main(){
    string str = "123456";
    //substr(pos): 提取从位置pos开始到末尾的子串。
    string a = str.substr(0);
    cout << a << endl; // 123456

}

substr(pos, len): 提取从位置pos开始的长度为len的子串

    //substr(pos, len): 提取从位置pos开始的长度为len的子串
    string b = str.substr(0, 2);
    cout << b << endl; // 12

2.2 截取特定字符前后的字符串,例如“.”

    string str = "123.456";
    string m, n;
    m = str.substr(0, str.find('.'));
    n = str.substr(str.find(".")+1);
    cout << m << "     " << n; //123     456

  1. 3.1 erase
    string ss = str.substr(0, 3);
    str.erase(0, 3); // 删除从0开始的3个字符
    str = str + ss;
    cout << str << endl; //456123
  1. 计算string的长度
int len = str.size();
  1. 字符串排序
    sort(str.begin(), str.end());
#include <iostream>
#include <string.h>
#include <algorithm>

using namespace std;

int main(){
    string str;
    cin >> str;
    sort(str.begin(), str.end());// dcdcba  --> abccdd
    cout << str <<endl;
}
  1. 字符串的倒转
#include <iostream>
#include <string>
#include <bits/stdc++.h>

using namespace std;
int main(){
    string str = "123.456";
    reverse(str.begin(), str.end());
    cout << str; //654.321
}

  1. 字符串内数字相加
    string a = "123456";
    string b = "456789";
    reverse(a.begin(), a.end());
    reverse(b.begin(), b.end());
    string ans = "";
    int carry = 0;
    for(int i = 0; i < a.size(); i++){
        int sum = (a[i] - '0') + (b[i] - '0') +carry;
        int remain = sum %10;
        char digit = '0' + remain;;
        ans = digit + ans;
        carry = sum /10;
    }
    if(carry == 1) ans = "1"+ ans;
    cout << ans << endl; //580245
  • 6
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值