Thevenin99
Thevenin99

Reputation: 33

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

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 don't love c++ I don't love c++

I have tried different things but I am not sure what is wrong

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

void WordReplace(string*x, int start, int end, string g, string w)
{
   for (int z = start; z <= end; z++)
   {
      if (x[z] == g)
         x[z] == w;

      cout << x[z]<<" ";
   }
}

int main()
{
   string x[4] = {"I", "don't", "hate", "c++"};

   for (int i = 0; i < 4; i++)
   {
      cout << x[i] << " ";
   }
   cout << endl;

   WordReplace(x, 0, 3, "hate", "love");

   cout << endl;

   return 0;
}

Upvotes: 0

Views: 6933

Answers (3)

Slava
Slava

Reputation: 44258

Just use std::replace:

std::string x[] = {"I", "don't", "hate", "c++"};
std::replace( std::begin( x ), std::end( x ), "hate", "love" );

live example

Upvotes: 5

schorsch312
schorsch312

Reputation: 5694

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

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

void WordReplace(vector<string> &sentence, string search_string,
             string replace_string) {
    for (auto &word : sentence) {
        if (word == search_string)
            word = replace_string;
    }
}

int main() {
    vector<string> 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<std::string> x {"I", "don't", "hate", "c++"};
std::replace( x.begin(), x.end(), "hate", "love" );

Upvotes: 2

user8496745
user8496745

Reputation:

If you want to assign a new value to a variable you need the following syntax:

myVar = myValue;

This will change the value of myVar to myValue.

This construction:

myVar == myValue

is a comparison and is treated as a bool, since it returned true(if myVar equals myValue) and False (if they are not equal). The construction doesn't change the value of myVar or myValue.

In your case you need to replace x[z] == w by x[z] = w, as suggested by Igor

Upvotes: 1

Related Questions