string用法总结

string常用操作

string的定义及赋值

#include<iostream>
#include<cstring>
#include<algorithm>

using namespace std;

int main()
{
	string s1="hellow world";
	string s2={"hellow world"};
	string s3(s1);
	cout<<s1<<endl<<s2<<endl<<s3<<endl;
	
	return 0;
}

string的长度

  • size()返回字符串长度
  • length()返回字符串长度(等价于size())
#include<iostream>
#include<algorithm>
#include<cstring>

using namespace std;

int main()
{
	string s;
	
	cin>>s;
	
	cout<<"字符串长度为"<<s.size();
	
	return 0;
}

判断字符串是否为空

  • empty()判断字符串是否为空,若为空则返回1,否则返回0
#include<iostream>
#include<algorithm>
#include<cstring>

using namespace std;

int main()
{
	string s1="hellow";
	string s2="";
	
	if(s1.empty()) cout<<"字符串s1为空"<<endl;
	else cout<<"字符串s1长度为"<<s1.size()<<endl;
	
	if(s2.empty()) cout<<"字符串s2为空"<<endl;
	else cout<<"字符串s2长度为"<<s2.size()<<endl;
	
	return 0;
}

清空字符串

  • clear()清空字符串
#include<iostream>
#include<algorithm>
#include<cstring>

using namespace std;

int main()
{
	string s="heoolw";
	
	s.clear();
	
	cout<<s<<endl;
	
	return 0;
}

字符串的反转

  • reverse()将字符串反转
#include<iostream>
#include<cstring>
#include<algorithm>

using namespace std;

int main()
{
	string s="hellow";
	
	reverse(s.begin(),s.end());
	
	cout<<s;
	
	return 0;
}

字符串的插入

  • push_back()在字符串末尾插入一个字符
#include<iostream>
#include<cstring>
#include<algorithm>

using namespace std;

int main()
{
	string s="heool";
	
	s.push_back('w');
	
	cout<<s;
	
	return 0;
}

字符串的截取

  • 格式1:s.substr(a,b);

    • 1、s 需要截取的字符串
    • 2、a 截取字符串的开始位置(注:当a等于0或1时,都是从第一位开始截取)
    • 3、b 要截取的字符串的长度
  • 格式2:s.substr(a) ;

    • 1、s 需要截取的字符串
    • 2、a 可以理解为从第a个字符开始截取后面所有的字符串。
#include<iostream>
#include<cstring>
#include<algorithm>

using namespace std;

int main()
{
	string s="hellow";
	
	string s1=s.substr(2,5);
	string s2=s.substr(2);
	
	cout<<s1<<endl;
	cout<<s2<<endl;
	
	return 0;
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值