- Home /
Edit a string C#
SO lets say I have a string:
public string Test = "OneTwo";
Now, I want to use a script to change it from "OneTwo" to "OneFour". I don't want to make a whole new string, I want to directly edit the string. Remove Two. Add Four. Thanks, if it's possible!
Just to be clear, I also don't want to do;
Test = "OneFour";
I want to do String.Format or something
Unlike in the C language, where "strings" are simply arrays of chars, strings in C#("true" strings) are immutable, meaning that, once created, their contents will not change. See $$anonymous$$SDN for more on this.
If what you are really asking is how to build the second string from the first (invariably resulting in a new string object), christoph_r has your answer. If you want to build longer strings with multiple concatenations (each concatenation creates a new string, as seen in the $$anonymous$$SDN page), you can try using the StringBuilder class.
Answer by christoph_r · Jul 01, 2014 at 09:39 PM
Take a look at string.Substring In your example this would be:
Test = Test.Substring(0,3); // 0 and 3 specify from and to which character the substring ranges
Test += "Two";
By the way: it's good practice to start variable names with a lower case letter.
Yes, that is exactly what I was looking for. Just a side question, is it possible to test for certain characters? For example: i want to test if the third character of the string "Test" is an e. Thank you!
bool CheckCharacter(int position, string testString, string testCharacter)
{
if(testString.Length >= position)
{
if(testString[position] == testCharacter)
{
return true;
}
else {
return false;
}
}
else {
return false;
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613152950im_/https://answers.unity.com/themes/thub/images/avi.jpg)