1、 字符串的分离
例如分离字符串
2011/03/04 00:00,385.968800,P,0001,M,0002,I |
为:
2011/03/04 00:00|385.968800|P|0001|M|0002|I |
字符串是以`,`作为隔离符,所以将判断是否是`,`作为条件,即,先读取要分离的字符串,然后从头开始查找,直到找到第一个不是`,`和空格(字符串的开头可能有多个空格),然后再查找,直到出现`,`,那么这之间的字符串,就可以分离出来。例如,先找到2,2满足条件。然后继续查找,找到`,`,那么2011/03/04 00:00 就是我们要分离的子串了。
bool is_comma(char c) { return (c==','); }
bool not_comma_space(char c) { return !is_comma(c)&&!isspace(c); } vector<string> split_str(const string str) { typedef string::const_iterator iter;
vector<string> ret;
iter i=str.begin();
while(i!=str.end())
{
i=find_if(i,str.end(),not_comma_space);
iter j=find_if(i,str.end(),is_comma);
if(i!=str.end())
ret.push_back(string(i,j));
i=j;
}
return ret; }
|
最终的字符串存放在一vector中。
2、 字符串中的替换
假如要将2011/03/04 00:00 中的`/`替换为`-`
Code:
while(lstr.find_first_of("/")!=string::npos) { int fk=lstr.find_first_of("/"); lstr.replace(fk,1,"-"); } |
加工下,使之成为通用的格式
void strreplace(string &str, string berep, string rep) { /** *str为要操作的字符串 *berep要被替换的字符串 *rep替换的字符串 */ while(str.find_first_of(berep)!=string::npos) { int fk=str.find_first_of(berep); str.replace(fk,1,rep); } }
|
3、 (undone)