下面是几个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;
}