- Home /
Replace the first string C#
Hey guy, I have a little question i don't find in the web. Can we replace the first string of an string? Here's a small exemple: "true && true && true && true", replace the first "true && true" by "double_true" then return "double_true && true && true".
First this true && true && true && true is a conditional statement with 4 booleans and the is no such thing as double_true.
Now if you are not talking about a boolean statement but you are talking about a string as in
string str = "true && true && true && true";
and you want to change it to
string str = "double_true && true && true && true";
then you would do if like so
string str = "true && true && true && true";
int result = str.IndexOf("true &&");
if (result >= 0)
{
str = "double_true && " + str.Substring(result + 8, str.Length - 8); // length of "true &&" is 8
}
Answer by jgodfrey · May 09, 2016 at 11:32 PM
You're looking for "string.replace". Here's an example:
string inString = "true && true && true && true";
string outString = inString.Replace("true && true", "double_true");
Debug.Log(outString);
Errrr... Wait. I now see that you just want to replace the first occurrence of the string. The above will replace all occurrences. I'll update the answer.
You can do it via Regex.Replace, like this:
string input = "true && true && true && true";
string output = Regex.Replace(input, "true && true", "double_true", 1);
Debug.Log(output);
Your answer
Follow this Question
Related Questions
Trying to Create Custom Encryption 1 Answer
Remove empty line from string 2 Answers
PlayerPrefs string to load scene (edited) 1 Answer
Simple networking - Sending string over network? 1 Answer
Multiple Cars not working 1 Answer