As the title says, I am trying to use the String.Replace() function, but it is not working as the information I have found suggests it should. It is currently not editing the target string at all. This is my current code which contains that function.
if(strTest.Contains("<name> ")){
genString = "<name>";
strTest.Replace(genString, "");
print(genString);
genString = strTest;
strTest = "has changed their name to " + strTest;
currentPlayer.name = genString;
}
genString = “”;
strTest.Replace(genString, “”);
isn’t this just saying “replace no character with no character”?
EDIT: as per @Eric5h5 's answer below, the Replace() function doesn’t modify a string. So…
Presumably, you’re trying to eliminate spaces from your string. If so, setting
genString = " ";
strTest = strTest.Replace(genString, "");
instead should do it.
This code doesn’t do anything:
genString = "";
strTest.Replace(genString, "");
Also, String.Replace returns a new string. It doesn’t change strings in-place. String.Replace Method (System) | Microsoft Learn
solution:
if(strTest.Contains("<name> ")){
genString = "<name>";
strTest = strTest.Replace(genString, ""); // I changed this line
print(genString);
genString = strTest;
strTest = "has changed their name to " + strTest;
currentPlayer.name = genString;
}
string.Replace();
get a new string but it doesn’t save it in any string variable, you should save it!
if(strTest.Contains(" ")){
genString = “”;
strTest = strTest.Replace(genString, “”);
print(genString);
genString = strTest;
strTest = "has changed their name to " + strTest;
currentPlayer.name = genString;
}
what changed, why?
here…
myString.replace(old , new);
This returns a value. The value needs to be stored. so if you want it to actually work use it like this:
myString = myString.replace(old , new);
hope, this helps after 8 years of people surfing through here and not giving this answer.