- Home /
String.Replace() not working
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;
}
ins$$anonymous$$d of strTest.Replace(genString, "");
do this strTest = strTest.Replace(genString, "");
Answer by Chris D · Jun 08, 2011 at 10:05 PM
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.
Problem with Unity Answers, suppressing text enclosed in '' - he does have stuff in his string.
oh. haha, welp ignore all this, then! Is the only way to see it by having edit privileges?
Answer by Eric5h5 · Jun 08, 2011 at 10:10 PM
This code doesn't do anything:
genString = "";
strTest.Replace(genString, "");
Also, String.Replace returns a new string. It doesn't change strings in-place. http://msdn.microsoft.com/en-us/library/system.string.replace.aspx
So would
genString = " ";
strTest = strTest.Replace(genString, "");
work, then?
Click "edit" on his question - he actually has stuff in there, but the new Unity Answers is trying to parse tags starting with '
Answer by Hassan-Kanso · Mar 01, 2015 at 07:56 AM
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!
Answer by lampartsygames · Aug 31, 2019 at 09:28 PM
if(strTest.Contains("<name> ")){
genString = "<name>";
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.
Your answer
Follow this Question
Related Questions
Question regarding chat-input? 1 Answer
Textfield doesnt work; it doesnt apply string 0 Answers
How to put a list of strings in a Text Unity 4.6 UI element 3 Answers
List of string is duplicated [C#] 1 Answer
Strange string appending 0 Answers