首页 新闻 赞助 找找看

程序如何精简一下?

0
[已解决问题] 解决于 2014-02-04 15:12

如题,我编写了一个查找\,,\:,\r,\n的4层嵌套if语句的程序,将字符串str中的所有上述4个字符删除,if -else 感觉有点绕,能不能帮忙精简一下,程序如下:

#include<string>
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

//功能: 循环删除字符串中的"\r" "\n""\,""\:"
string StrClean(const string &strSource)
{
    string strDes = strSource;
    string::size_type index = 0;
    do
    {
        index = strDes.find("\\:");
             if (index != string::npos)
             {
              strDes = strDes.replace(index, strlen("\\:")," ");
             }
             else
             {            
                       index = strDes.find("\\r");
                       if (index != string::npos)
                         {
                           strDes = strDes.replace(index, strlen("\\r")," ");
                         }
                       else
                       {
                           index = strDes.find("\\n");
                           if (index != string::npos)
                           {
                               strDes = strDes.replace(index, strlen("\\n")," ");
                           }
                           else
                           {
                               index = strDes.find("\\,");
                               if (index != string::npos)
                               {
                                   strDes = strDes.replace(index, strlen("\\,")," ");
                               }
                           }
                       }
             }
    } while (string::npos != index);
    return strDes;
}


int main()
{
    string str = "123\:12\,esg\rsf\n if \: will my name\, gs\r\ntf\vs\r\nc",stre;
    cout << "the source string is :" << str << endl;
    //str.remove("\r\n");
    //str.replace("\r\n", "");
    stre=StrClean(str);
    cout << "the destination string is :" << stre << endl;
    return 0;
}

xx ee的主页 xx ee | 菜鸟二级 | 园豆:206
提问于:2014-01-22 01:00
< >
分享
最佳答案
1

代码看不懂,我的方向是C#。 但我可以给你个建议, 就是用 “正则” 进行字符替换。 好处是效率高, 而且不用循环移除, 多重循环对性能影响是很大的, 不建议使用

奖励园豆:5
Jerry柯 | 菜鸟二级 |园豆:496 | 2014-01-22 10:39

嗯 是的  我处理大量文件时发现了,需要改进

xx ee | 园豆:206 (菜鸟二级) | 2014-01-22 19:36
其他回答(2)
0

switch case 呢?可以尝试一下。感觉你的代码过度混乱。而且,目的不够明确,\v不处理?

勇敢的劳油条 | 园豆:21 (初学一级) | 2014-01-22 11:21
0

char [] s={"\r","\n","\,",……}

string  str=str.trim(s);

大楚打码人 | 园豆:4313 (老鸟四级) | 2014-01-22 15:05

这个没用过,查查看

支持(0) 反对(0) xx ee | 园豆:206 (菜鸟二级) | 2014-01-22 19:36
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册