Replace the middle of a string with only 3 chars

What can I use to replace the middle char in a string like this: 000 becomes 010.

Do I have to do it with Regex, if yes, can i have the pattern? Or just with the String.Replace method?

Info: There are always numbers in the string.


check these links

hope these links help u

There is no clear logic behind the replace procedure, looking on the question, but assuming that you at some point know which symbol should appear in the middle,

can create an extension method, say like this

public static class Extension
    public static string ReplaceMiddle(this string value, char charToPutIn)
        var builder = new StringBuilder(value);
        builder[value.Length/2] = charToPutIn;
        return builder.ToString();


and after use this like this:


which will produce result like:


as expected.

If it's only a 3 character string:

String number = "123";
String res = number[0] + "5" + number[2];

 string s = "111000111";
 string pattern = "000";
 string replacement = "010";
 Regex rgx = new Regex(pattern);
 string result = rgx.Replace(s, replacement);
 lbloriginal.Text = s;
 lblnew.Text = result;           

Replacing characters or substrings by index is a bit awkward to do. It would boil down to

string newString = str.Substring(0,1) + newChar + str.Substring(2);

It is much easier by content where you can use the Replace method to replace a substring by another.

Regex would be an option, but even then it's not pretty:

Regex.Replace(str, "^(.).(.)$", "${1}1$2"

Need Your Help

How do I cancel a server control event in the client side? events validation

I have an image button and I want to cancel the click event incase he fails the client side validation... how do I do that?

Populate dropdownlist with datareader from database

c# sqldatareader

Problem with populate specific dropdownlist values from database, i want to shows user all the current data from database tables to let them able to make changes, but i coulnd't shows the specific