栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

c++ string的使用

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

c++ string的使用

c++ string的使用

1. 第一步,引入库

1.1 参数说明 2. 初始化3. 获取字符串元素4. 字符串长度5. 插入6.获取子串7.替换字符8.类型转换
参考了 cppreference

1. 第一步,引入库
#include 
1.1 参数说明

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

2. 初始化
string str="abaa";
cout< 
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< 
5. 插入 
    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'
    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.替换字符
    replace(int index, int len, const char* str)
string s = "xmplr";
s.replace(2,3,"AA");
cout << s << 'n'; // xmAA
    replace(int index, int len, int count, char ch)
string s = "xmplr";
s.replace(2,3,2,'A');
cout << s << 'n';
8.类型转换
    字符串string转化为int类
    stoi()
string str1 = "45";
int myint1 = stoi(str1); // 45
    int转化为string
    to_string()
int myint1 = 456;
string bo = to_string(myint1); // "456"

double mydb = 456.12050;
string bo = to_string(mydb);
cout<
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/766808.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号