c++ string的使用


参考了 cppreference

1. 第一步,引入库

#include <string>

1.1 参数说明

index:起始下标(从0开始)
len:长度
count:数量
ch:字符

2. 初始化

string str="abaa";
cout<<str<<endl; // 输出 abaa

3. 获取字符串元素

用[]或者at(int index)都可以

string str="abaa";
char a = str[2]; // a: a
char b = str.at(2); // b: a

4. 字符串长度

string s = "abaazzzzz";
cout<<s3.length()<<endl; // 输出9
cout<<s3.size()<<endl; // 输出9

5. 插入

  1. append() 在字符串的末尾添加字符或字符串
    string str2 = "hello";
    
    string str="abaa";
    string s1 = str.append(str2); // abaahello
    str = "abaa";
    string s2 = str.append(str2, 3, 2); // abaalo,在str末尾添加从str2的第3个字符(从0开始)开始的2个字符
    str = "abaa";
    string s3 = str.append(5, 'z'); // abaazzzzz,在str末尾添加5个'z'
  1. insert()
    a. insert(int index,int count, char ch)
string s = "xmplr";
s.insert(0,2,'A');
cout << s << '\n'; // AAxmplr

b. insert(int index, const char* s)

string s = "xmplr";
s.insert(2,"eEA");
cout << s << '\n'; // xmeEAplr

6.获取子串

substr()

string a = "0123456789abcdefghij";
string sub1 = a.substr(10);
cout << sub1 << '\n'; // abcdefghij

string sub2 = a.substr(5, 3); //返回从从pos处开始的count个字符,若count超出字符串长度,则返回后面全部
cout << sub2 << '\n'; // 567

7.替换字符

  1. replace(int index, int len, const char* str)
string s = "xmplr";
s.replace(2,3,"AA");
cout << s << '\n'; // xmAA
  1. replace(int index, int len, int count, char ch)
string s = "xmplr";
s.replace(2,3,2,'A');
cout << s << '\n';

8.类型转换

  1. 字符串string转化为int类
    stoi()
string str1 = "45";
int myint1 = stoi(str1); // 45

string str2 = "-45";
int myint2 = stoi(str2); // -45
cout<<myint2;
  1. int转化为string
    to_string()
int myint1 = 456;
string bo = to_string(myint1); // "456"

double mydb = 456.12050;
string bo = to_string(mydb);
cout<<bo<<endl; // "456.120500"
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值