-5

Here's my string: String s = "X0001";

Now I want to replace X with N.

i.e String s = "N0001;

How can I do this?

i Dont Know
  • 75
  • 1
  • 3
  • 8

2 Answers2

0

You can use Replace:

String s = "X0001";
s = s.Replace('X', 'N');

With this, Console.WriteLine(s) will output

N0001

Thomas Ayoub
  • 29,063
  • 15
  • 95
  • 142
0

If you want to replace all, use String.Replace:

s = s.Replace("X", "N");

If you want to replace the first;

s = "N" + s.Substring(1);

If you have something like <xml><Name>X0001</Name> and you want to replace X0001 with N0001 you can use string methods ( or XML libraries):

string xml = "<xml><Name>X0001</Name>";
int start = xml.IndexOf("<Name>", StringComparison.InvariantCultureIgnoreCase);
if (start >= 0)
{
    start += "<Name>".Length;
    int end = xml.IndexOf("</Name>", start, StringComparison.InvariantCultureIgnoreCase);
    if (end >= 0)
    {
        string before = xml.Substring(0, start);
        string token = xml.Substring(start, end - start);
        string after = xml.Substring(end);
        if (token.Length > 0)
            xml = string.Format("{0}{1}{2}", 
                before, 
                token.Replace("X", "N"), 
                after);
    }
}
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
  • thanks Tim..if for example the String in XML like X0001..in this situation how can i cahnge X0001 to N0001...pls give me reply – i Dont Know May 11 '15 at 13:29
  • 1
    @iDontKnow: so now your input changes to `X0001`? Are you sure that the next question won't be "how to modify the xml file"? – Tim Schmelter May 11 '15 at 13:30
  • @iDontKnow: have a look. – Tim Schmelter May 11 '15 at 13:39
  • @iDontKnow, I think you need 200K rep to parse XML with `string.IndexOf`... :) And 600K to use regular expression to do that... Please use `XDocument` to deal with XML... – Alexei Levenkov May 11 '15 at 13:54
  • 1
    @AlexeiLevenkov: i didn't want to deviate from the original question too much which was about a single string. Now it seems to be still a single string which is a little bit longer. If it's getting a whole xml file OP should ask a different question. – Tim Schmelter May 11 '15 at 13:57