C++ string split()和 replaceAll()

清华大佬耗费三个月吐血整理的几百G的资源,免费分享!....>>>

#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; 
}