C++ string split()和 replaceAll()

2018-07-20    来源:open-open

容器云强势上线!快速搭建集群,上万Linux镜像随意使用
#include "stdafx.h"
#include <iostream> 
#include <string> 
#include <vector> 
 
 
using namespace std; 
 
 
vector<string> mySplit(const string& str, string sp_string)  // split(), str 是要分割的string
{ 
    vector<string> vecString; 
    int sp_stringLen = sp_string.size(); 
    int lastPosition = 0; 
    int index = -1; 
    while(-1 != (index=str.find(sp_string , lastPosition))) 
    { 
        vecString.push_back(str.substr(lastPosition, index - lastPosition)); 
        lastPosition = index +sp_stringLen; 
    } 
    string lastStr = str.substr(lastPosition); 
    if ( !lastStr.empty() ) 
    { 
        vecString.push_back(lastStr); 
    } 
    return vecString; 
} 
 
 
string myReplaceAll(const string& str, string org_str, string rep_str) // 把org_str 替换为rep_str; 
{ 
    vector<string>  delimVec = mySplit(str, org_str); 
    if (delimVec.size() <= 0) 
    { 
        cout<<"can not find"<<endl; 
        return str; 
    } 
    string target(""); 
    vector<string>::iterator it = delimVec.begin(); 
    for (; it != delimVec.end(); ++it) 
    { 
        target = target + (*it)+ rep_str; 
    } 
//target = target +(*it); 
    return target; 
    } 
 
// 把org_strVec中的string全部替换为rep_str; 
string myReplaceAll(const string& str, vector<string>& org_strVec, string rep_str)
{ 
    vector<string>::iterator org_it = org_strVec.begin(); 
    string org_str(""); 
    string target = str; 
    string strTarget = str; 
    for (; org_it != org_strVec.end(); ++org_it) 
    { 
        org_str = *org_it; 
        vector<string> delimVec = mySplit(strTarget, org_str); 
        target = ""; 
        if (delimVec.size() > 0) 
        { 
            vector<string>::iterator it = delimVec.begin(); 
            for (;it != delimVec.end(); ++it) 
            { 
                target = target + (*it) +rep_str; 
            } 
            strTarget = target; 
        } 
    } 
    return strTarget; 
} 
 
 
 
 
int _tmain(int argc, _TCHAR* argv[]) 
{ 
    string str = "ewrsdrtwrtsdfsdsdfrtfgsdfertgdffgertsdfsd"; 
    string splitStr = "sd"; 
    string replaceStr1 = "mmmm"; 
    string replaceStr2 = "xxxx"; 
    vector<string> strVec1 = mySplit(str, splitStr); 
    for (vector<string>::iterator it = strVec1.begin(); it != strVec1.end(); ++it) 
    { 
        cout<< "!!!  "<<*it<<endl; 
    } 
    string strX[] = {"wr","rt"}; 
    vector<string> strVec2 (strX, strX + sizeof(strX)/sizeof(strX[0])); 
 
    cout << strVec2[0]<<"13q3224"<<strVec2[1]<<endl; 
    str = myReplaceAll(str,splitStr,replaceStr1); 
    str = myReplaceAll(str,strVec2,replaceStr2); 
    cout << str <<"~~~~~"<<endl; 
    return 0; 
}

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点!
本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。

上一篇:Java对 Double 类型的数据进行四舍五入

下一篇:纯JavaScript分页插件