关于字符串处理的应用扩展

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值