一、用C++分隔字符串
我们都知道,Shell中的awk用来处理字符串十分方便,可在C++中就没有那么容易了。有这样一个需求:
假设文本内容如下所示:
zhangsan | 3456123, hunan
lisi, 4564234 | hubei
wangwu, 4433253,beijing
我们需要以"|" ","为分隔符,同时又要过滤空格,把每行分成相应的字段进行输出。
C++中的string中有find,find_first_of,find_first_not_of等函数,用来处理字符串是再合适不过了。下面是具体的代码:
#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
#include<iterator>
#include<functional>
#include<fstream>
#include<cassert>
using namespace std;
int main()
{
ifstream fin("D:\\data.txt");
if (!fin)
{
cout << "Open file error!" << endl;
return -1;
}
string str;
string strset = "|, ";
int pos = 0;
while (getline(fin, str))
{
cout << "------------------------" << endl;
cout << str << endl;
cout << "after processed:" << endl;
int first(0);
while ((first=str.find_first_not_of(strset,first)) != string::npos)
{
int last = str.find_first_of(strset,first);
if (last == string::npos)
{
cout << str.substr(first) << endl;
break;
}
cout << str.substr(first, last - first )<<endl;
first = last+1;
}
pos = 0;
cout << endl;
}
fin.close();
system("pause");
return 0;
}
2.用C++ string 替换字符串
C++ string中字符串替换函数replace的原型只提供了按位置或区间的操作,而不能实现用一个字符串替换另一个字符串的功能。这个简单,自己写一个替换函数呗。
void string_replace(string& str, const string& strsrc, const string& strdst)
{
if (str.size == 0)
cerr << "invalid string!" << endl;
string::size_type pos = 0;
string::size_type strsrclen = strsrc.size();
string::size_type strdstlen = strdst.size();
while ((pos = str.find(strsrc, pos) )!= string::npos)
{
str.replace(pos, strsrclen, strdst);
pos += strdstlen;
}
}
主函数如下:
int main()
{
string str = "2014,ustc! ustc is the university where my friend had studied!";
cout << str << endl;
cout << "after replace,the string is :" << endl;
string_replace(str,"ustc","zju");
cout << str << endl;
system("pause");
return 0;
}