c++ replaceAll

c++ replaceAll

#include
#include
#include
int ReplaceAll(const std::string& input,const std::string& substr,const std::string& repstr, std::string& output)                                        
{
        int replaceCount = 0;
        std::stringstream ss;
        size_t i = 0;                                                               
       
        while(i < input.length())
        {                                                                           
        std::cout << "i:" << i << std::endl;
        size_t left_len = input.length() - i - 1;
        std::cout << "left_len:" << left_len << std::endl;
                if (left_len < substr.length())                                     
                {
                        ss << input.substr(i);                                      
                        break;
                }                                                                   
       
                if (input.substr(i,substr.length()) == substr)                      
                {
                        i += substr.length();                                       
                        ss << repstr;
                        ++replaceCount;
                }
                else                                                                
                {
                        ss << input[i];                                             
                        ++i;                                                        
                }                                                                   
        }
                                                                                    
        output = ss.str();                                                          
        return replaceCount;
}

int main()
{
    std::string a("wel--com--e");
    std::cout << a.substr(0,2) << std::endl;
    std::string sub("--");
    std::string rep("$");
    std::string output;
    if (ReplaceAll(a,sub,rep,output))
    {
        std::cout << output << std::endl;
    }

    return 1;
}

posted on 2013-12-20 15:36  lexus 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/lexus/p/3483978.html

你可能感兴趣的:(c++ replaceAll)