string介绍

string字符串
所在的库#include< string >
基本功能介绍
1 查找
格式 a.find(“b”,pos);
从字符串a中的pos位置开始查找b
函数返回值 b所在的位置
找不到 函数返回值 -1

#include<iostream>
#include<string>
using namespace std;
int main(){
	string a="abcdefg";
	cout<<a.find("de",0)<<endl;
	return 0;
}

2.替换
a.place(i,n,b);
a字符串从i开始替换n个字符为字符串b
函数返回值是 替换后完整的字符串

#include<iostream>
#include<string>
using namespace std;
int main(){
	string a="xxxoooxxx";
	//从a中的第3个位置开始替换其中的两个字符 
	cout<<a.replace(3,2,"xxx")<<endl;
	return 0;
}

3.获取字符串长度
length(),size();
返回值=字符串的长度

#include<iostream>
#include<string>
using namespace std;
int main(){
	string a="xxxoooxxx";
	cout<<a.length()<<endl;
	cout<<a.size()<<endl;
	return 0;
}

4.判空
a.empty();
空返回=1,非空返回=0;

#include<iostream>
#include<string>
using namespace std;
int main(){
	string a="xxxoooxxx";
	string b;
		cout<<a.empty()<<endl;
		cout<<b.empty()<<endl;
	return 0;
}

5.插入字符串
str1.insert(n,str2)
从str1的n位置插入str2字符串
返回值=插入后的字符

#include<iostream>
#include<string>
using namespace std;
int main(){
	string a="xxxoooxxx";
	string b="ttt";
		cout<<a.insert(3,b)<<endl;
	return 0;
}

拓展:

string s1=“hello”;
s1.insert(1.“ins”);//从s1的位置1开始,插入"ins"字符串,即s1=“hinsello”;
s1.insert(1,“ins”,2)//从s1的位置1 开始,插入"ins"字符串的前两个字符,即s1="hinello;
s1.insert(1,“ins”,1,2)//从s1的1位置开始,插入"ins"字符串从1位置开始的2个字符,即s1=“hnsello”;

6.删除字符串
str.erase(n,m)
删除str字符串从n开始的m个字符
返回值=删除后的字符串

#include<iostream>
#include<string>
using namespace std;
int main(){
	string a="xxxoooxxx";
	string b="ooo";
		
		cout<<a.erase(3,3)<<endl;
	return 0;
}

7.截图字符串字段
str.substr(a,b);
截取字符串a位置到b位置
返回值=截取的字段
注意:不会改变原来的字符串

#include<cstdio>
#include<string>
#include<iostream>
using namespace std;
int main(){
	string str="abcdf";
	cout<<str.substr(1,3)<<endl;
	cout<<str<<endl;
	return 0;
} 
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值