string字符串常见用法

string是C++标准库中的类,掌握后会让编程事有半功倍的效果,使用时要包含头文件#include< string >,加上using namespace std;
下面介绍string中常见的一些用法

1.查找
int a.find(str,pos);
从a字符串中查找str字符串,从pos位置开始查找,
返回值=str字符串第一次出现的位置
如果没有找到返回值为-1;

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

在这里插入图片描述
2.替换
a.place(i,n,str);
a字符串从i开始替换n个字符为字符串str
(可以理解为n个字符直接删掉,将str字符串插入)
注意:a的值会改变为替换后的
返回值=替换后的字符串

#include<iostream>
#include<string>
using namespace std;
int main(){
	string a="xxxoooxxx";
	cout<<a.replace(3,3,"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;
} 

在这里插入图片描述

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值