C++ String字符串处理常用函数

下面是几个string类用于提取字符串的常用方法:

1.str.find(str2,pos):从str的pos位开始查找匹配str2,并返回其在str中第一次出现的位置,pos没有赋值的话默认为0

string str1="test";
string str2="t";
unsigned int index;
if(str1.find(str2)!=string::nops) //判断str2是否为str1的子串
{
    index=str1.find(str2);//此时默认返回从字符串开始匹配到的第一个子字符串的位置,也就是0
    index=str1.find(str2,index+1);//此时从第二个字符开始查找相匹配的字符串,所以返回3
}

2.str.erase(first,last):first和last均为迭代器,删除[first,last)之间的所有元素,last没有赋值的话只删除first处的元素;

  str.erase(pos,len):pos为unsigned int 类型,删除从pos为开始的长度为len的字符串;

3.str.substr(pos,len):返回从pos位开始的长度为len的字符串;

4.str.insert(pos,str2):在pos位插入str2;

   str.insert(it,it1,it2):在str的迭代器it处插入str2从it1到it2的子字符串;

下面的程序用于取出括号内逗号相隔的子字符串并存储在map容器中:

// test.cpp: 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include<algorithm>
#include<map>
#include<queue>
#include<iostream>
#include<string>

using namespace std;

void str_deal(string str, map<string, int> mp[], int &index)
{
	string str_find1 = "(";
	string str_find2 = "NULL";
	string str_find3 = ")";
	string str_find4 = ",";
	string str_first;
	unsigned int back_pos;
	unsigned int front_pos;
	unsigned int last_pos;
	unsigned int next_pos;

	string str_get;

	front_pos = str.find(str_find1);
	back_pos = str.find(str_find3);
	str_first = str.substr(0, front_pos);
	mp[index][str_first] = index;

	last_pos = front_pos;
	if (str.find(str_find2) == string::npos)
	{
		next_pos = str.find(str_find4, last_pos);
		while (next_pos <= back_pos)
		{
			index++;
			str_get = str.substr(last_pos + 1, next_pos - last_pos - 1);
			mp[index][str_get] = index;
			last_pos = next_pos;
			next_pos = str.find(str_find4, last_pos+1);
		}
	}
}
int main()
{
	string str = "task0(task1,task2,task3,task4,task5)";
	map<string, int> mp[10000];
	int index = 0;
	int i = 0;
	str_deal(str, mp, index);
	map<string, int>::iterator it;

	while (i<=index)
	{
		it = mp[i].begin();
		cout << it->first<<" ";
		i++;
	}
	system("pause");
	return 0;
}


 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值