c++ how to replace a string in an array for another string

前端 未结 3 978
逝去的感伤
逝去的感伤 2021-01-26 06:43

I am trying a short code that uses an array, I basically want to replace the word hate for love when I call my function WordReplace but I keep printing the same thing:

I

3条回答
  •  星月不相逢
    2021-01-26 06:57

    You have c++. Use proper containers (e.g. std::vector).

    #include 
    #include 
    #include 
    using namespace std;
    
    void WordReplace(vector &sentence, string search_string,
                 string replace_string) {
        for (auto &word : sentence) {
            if (word == search_string)
                word = replace_string;
        }
    }
    
    int main() {
        vector sentence{"I", "don't", "hate", "c++"};
    
        for (const auto word : sentence)
            cout << word << " ";
        cout << endl;
    
        WordReplace(sentence, "hate", "love");
    
        for (const auto word : sentence)
            cout << word << " ";
        cout << endl;
    
         return 0;
    }
    

    or even better, don't reinvent the wheel

    std::vector x {"I", "don't", "hate", "c++"};
    std::replace( x.begin(), x.end(), "hate", "love" );
    

提交回复
热议问题