C++--string类-字符串操作

35 篇文章 0 订阅

cplusplus reference–string
cppreference–string

string类的字符串操作

  • find – 在字符串中查找内容
void test12()
{
	string str = "12345abcd123456789";
	string str2 = "123456789";
	size_t pos = str.find(str2); //9 第九个位置
	pos = str.find("abc", 5, 3); //5 第五个位置
	pos = str.find('a'); // 5 第五个位置
	pos = str.find("xyz"); //4294967295  即-1  未找到
}
  • rfind – 查找字符串最后的内容
  • substr --生成字串,返回新构建的对象,其值初始化为此对象的子串的副本。
void test13()
{
	//正向查找
	string str = "http://www.cplusplus.com/reference/string/string/substr/";
	size_t pos = str.find("://");
	if (pos != string::npos)
	{
		size_t pos2 = str.find("/", pos + 3);
		if (pos2 != string::npos)
		{
			pos += 3;
			string sub = str.substr(pos, pos2 - pos);
			cout << sub << endl; //www.cplusplus.com
		}
	}
	//反向查找
	string str2 = "test.txt.tar.gz.cpp";
	size_t pos2 = str2.rfind(".");
	if (pos != string::npos)
	{
		cout << str2.substr(pos2 + 1); //cpp
	}
}
  • find_first_of – 查找字符串中的字符,搜索与其参数中指定的任何字符匹配的第一个字符
  • find_last_of – 查找字符串中的字符,搜索与其参数中指定的任何字符匹配的最后一个字符
  • find_first_not_of – 搜索字符串,查找与其参数中指定的任何字符不匹配的第一个字符
  • find_last_not_of – 搜索与参数中指定的任何字符不匹配的最后一个字符的字符串
void test14()
{
	string str = "1234abcd123abc";
	size_t pos;
	pos = str.find_first_of("abc",0); //4 匹配第一个字符a
	cout << pos << endl;
	pos = str.find_last_of("123"); //10 匹配最后一个字符3
	cout << pos << endl;
	pos = str.find_first_not_of("123a",0); // 3 返回在字符串中首次不匹配123a的字符索引
	cout << pos << endl;
	pos = str.find_last_not_of("389"); //13 返回在字符串中最后一次不匹配389的字符索引
	cout << pos << endl;
}
  • 7
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值