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

c++ string常见用法汇总

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

c++ string常见用法汇总

1. string 的初始化
#include 
#include 

string s1 = "aaaa";
string s2("bbbb");
string s3 = s2;
string s4(10, 'a');
2. string 的遍历
string s1 = "abcdefg";
//数组方式
for(int i =0; i
    cout << s1[i] <
	cout<< *it <
    cout << s1.at(i) < 
3. 字符指针和string的转换 
//      char *  ===> string
string s1 = "aaa";

//    string ===> char *
printf("%sn", s1.c_str());

// 把string中的内容copy到char *类型的buf中
char buf[128];
s1.copy(buf, 3 ,0);           从位置0开始拷贝3个到buf中
4. 字符串的连接
string s1 = "aaa";
string s2 = "bbb";
//(1)方式一
s1 = s1 + s2;
cout << s1 < 
5. 字符串的查找和替换 
#include 
#include 
#include "algorithm"

//(1) 查找字符串的下标
string s1 = "who hello 111";
int index = s1.find("who", 0);  //0表示偏移量,从哪开始查,     失败返回 -1
cout << index <
	count ++;
	cout << offindex < 
6. 字符串的删除和替换 
//(1)删除	
string s1 = "hello1 hello2 hello3";
string::iterator it = find(s1.begin(), s1.end(), 'l');
if(it != s1.end())
{
	s1.erase(it);  // 输出  helo1 hello2 hello3
}
s1.erase(s1.begin(), s1.end());  // 全部删除 区域删除

//(2)插入
string s2 = "bbb";
s2.insert(0, "AAA");  //输出  AAAbbb		
s2.insert(s2.length(), "ccc");  //输出  AAAbbbccc
7. 字符串转大写和转小写

函数原型

transform(...,...,...,...,...);     

第1, 2个参数表示转换范围,3个参数表示转换后存储的位置,第4参数表示转换方法

string s1 = "AAAbbb";
transform(s1.begin(), s1.end(), s1.begin(), toupper);//转大写  
//输出AAABBB

string s2 = "AAAbbb";
transform(s1.begin(), s1.end(), s1.begin(), tolower);//转小写   
//输出aaabbb  
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/853359.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

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

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