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?
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?
You can use Replace:
String s = "X0001";
s = s.Replace('X', 'N');
With this, Console.WriteLine(s)
will output
N0001
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);
}
}