C ++如何将数组中的字符串替换为另一个字符串 [英] c++ how to replace a string in an array for another string
问题描述
我正在尝试一个使用数组的短代码,我基本上想在调用函数WordReplace时替换仇恨一词,但我会继续打印相同的东西:
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:
我不爱c ++ 我不喜欢c ++
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;
}
推荐答案
如果要为变量分配新值,则需要以下语法:
If you want to assign a new value to a variable you need the following syntax:
myVar = myValue;
这会将myVar的值更改为myValue.
This will change the value of myVar to myValue.
此构造:
myVar == myValue
是一个比较,被视为布尔值,因为它返回true(如果myVar等于myValue)和False(如果它们不相等).该构造不会更改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.
根据您的情况,按照Igor的建议,您需要将x[z] == w
替换为x[z] = w
In your case you need to replace x[z] == w
by x[z] = w
, as suggested by Igor
这篇关于C ++如何将数组中的字符串替换为另一个字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!