c++实现字符串分隔

来源:互联网 发布:上古世纪捏脸数据在那 编辑:程序博客网 时间:2024/05/21 18:11
#include <iostream>
#include <string>
#include <vector>
using namespace std;


void split(string s, vector<string>& parts)
{
int start = 0; // 每一分段的开始位置


while (start < s.size())
{
int end = start;//end每一分段的结束位置
while (isdigit(s[end])||isalpha(s[end]))
end++;
if (end > start)
{
string temp = s.substr(start, end - start);//不含标点符号,不用多加1
parts.push_back(temp);
}
start = end + 1;
}
}




int main()
{
string s = "\thello,world,,good,\tmorning ";//27个,如果一开始就有分隔符,则不处理,直到遇到有效字符,才开始记录start = i;然后遇到分隔符时,使text[i]='\0'
//字符串里面不能有\0,否则\0后面的字符读取不到比如"\0hello,world,,good,\tmorning ",则读取\0之后就结束了,后面一个字符都读取不到


vector<string> results;
split(s, results);


for (int i = 0; i < results.size(); i++)
cout << results[i] << endl;


return 0;
}
0 0