C++:常用的string类字符串函数(二)

想了解字符串string类的基本用法,可参见:C++:string类的基本用法(一)


常用的字符串函数包括:复制、拼接、查找字符、截短、反转、大小写转换等。使用这些字符串函数,能够轻松的解决很多字符串操作问题,并且使你的代码变得更加简洁可读。

1 拼接字符串append()

要将两个字符串拼接在一起,可以使用运算符+=,也可以使用成员函数append():

#include<iostream>
#include<string>
using namespace std;

int main()
{
	string s1("I love");
	string s2(" you!");
	//方法1:+=
	s1+=s2;
	cout<<s1<<endl;
	//方法2:append()
	string s3(" I love you very much!");
	s1.append(s3);
	cout<<s1<<endl;
	return 0;
} 

2 查找字符或者子字符串find()

string类的成员函数find,可以用来查找字符串中的字符和子字符串,比如:

//从索引为n的位置开始,查找字符串s1中的子串s2,并返回给pos。(其中,s2可以是字符也可以是子字符串)
int pos=s1.find(s2,n);
#include<iostream>
#include<string>
using namespace std;

int main()
{
	string s1("I love you! and do you love me?");
	cout<<"s1:"<<s1<<endl;
	
	//1.从最开始处开始搜索,返回字符串love第一次出现的位置 
	size_t position= s1.find("love",0);
	if(position!=string::npos) //string:npos实际值为-1,表示没有找到要搜索的元素
		cout<<"字符串love第一次出现的位置:"<<position<<endl;
	else
		cout<<"字符串love没有被找到"<<endl; 
		
	//2.返回所有子字符串的位置
	cout<<"字符串love出现的所有位置:"; 
	size_t all_pos=s1.find("love",0);
	while(all_pos!=string::npos)
	{
		cout<<all_pos<<" ";
		size_t  search_pos=all_pos+1;
		all_pos=s1.find("love",search_pos); //返回子字符串出现的位置 
	} 
	return 0;
} 

3 截短字符串erase()

(1)给定偏移位置(删除的起始位置)和要删除的字符个数。

string s1 = "I love you very much!"
s1.erase(2,4); //从索引号2开始,删除4个字符,即删掉love。

(2)在给定指向字符的迭代器时删除该字符

//删除字符串s1中的所有的字符'I'
#include<iostream>
#include<string>
#include<algorithm>
using namespace std;

int main()
{
	string s1("I love you! and do you love me?");
	string::iterator pos = find(s1.begin(),s1.end(),'I'); //找到字符'I'的位置给迭代器
	if(pos!=s1.end())
		s1.erase(pos); //依次删除迭代器指向的字符
	cout<<s1<<endl;
	return 0;
} 

(3)在给定两个迭代器指定的范围时,删除该范围内的字符

s1.erase(s1.begin(),s1.end());

4 字符串反转reverse()

所谓反转,就是首位倒序存放。比如要判断某字符串是否是回文串,就可以将其反转,再与原来的字符串进行比较。

#include<iostream>
#include<string>
#include<algorithm>
using namespace std;

int main()
{
	string s1("I love you!");
	reverse(s1.begin(),s1.end());  //将s1进行反转
	cout<<s1;
	return 0;
} 

5 大小写转换transform()

//1.将字符串s1转换为大写
transform(s1.begin(),s1.end(),s1.begin(),toupper);
//2.将字符串s1转化为小写
transform(s1.begin(),s1.end(),s1.begin(),tolower);
发布了51 篇原创文章 · 获赞 135 · 访问量 5061

猜你喜欢

转载自blog.csdn.net/wjinjie/article/details/105092912