Accepted answer

For your interviewer

string output = new String(input.Select(ch => ch == '2' ? '0' : ch).ToArray());

I think intend was to see if you understand that string could be treated as sequence of characters. Interviews often have questions not related to real-life programming. I personally hate questions about inheritance tree with new modifiers.


Why you need to do it with LINQ, simple string.Replace should do the trick.

string str = "21212121".Replace("2","0");

EDIT: If you have to use LINQ then may be something like:

string  newStr = new string(str.Select(r => (r == '2' ? '0' : r)).ToArray());


For changing a single character you can use the overload of Replace that takes char arguments:

string s = "21212121";
s = s.Replace('2', '0');

This is likely to be slightly more efficient than the overload that accept strings.

If you absolutely have to use LINQ for some reason, then you can do this:

s = new string(s.Select(c => c == '2' ? '0' : c).ToArray());

But you shouldn't do this in production code. It's harder to read and less efficient than string.Replace.


string strInput = "21212121";

char from = '2';
char to = '0';

var strOutput = new string(strInput.Select(c => c.Equals(from) ? to : c)


Related Articles