razzv razzv - 3 months ago 26
C# Question

How do I replace specific characters from a c# string?

if I have a string along the lines of: "user:jim;id:23;group:49st;"
how can I replace the group code (49st) with something else, so that it shows: "user:jim;id=23;group:76pm;"

sorry if the question is easy but I haven't found a specific answer, just cases different than mine.


You can use the index of "group" like this

string s = "user:jim;id:23;group:49st;";
string newS = s.Substring(0,s.IndexOf("group:") + 6);
string restOfS = s.IndexOf(";",s.IndexOf("group:") + 6) + 1 == s.Length 
? "" 
: s.Substring(s.IndexOf(";",s.IndexOf("group:") + 6) + 1);
newS += "76pm;";
s = newS + restOfS;

The line with the s = criteria ? true : false is essentially an if but it is put onto one line using a ternary operator.

Alternatively, if you know what text is there already and what it should be replaced with, you can just use a Replace

s = s.Replace("49st","76pm");

As an added precaution, if you are not always going to have this "group:" part in the string, to avoid errors put this inside an if which checks first