I am trying to replace string in a text file.
I use the following code:
string text = File.ReadAllText(@"c:\File1.txt");
text = text.Replace("play","123");
File.WriteAllText(@"c:\File1.txt", text);
It not only changes the word "play" to "123" but also change the word "display" to "dis123"
How to fix this problem?
You could take the advantage of "Regular expressions" here.
\b
Matches the word boundary, This will solve your problem.
text = Regex.Replace(text, @"\bplay\b","123");
Read more about Regular expressions
You can use following snippets of code
var str = File.ReadAllText(@"c:\File1.txt");
var arr = str.Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries).ToList();
for (int i = 0; i < arr.Count; i++)
{
if (arr[i].StartsWith("play"))
{
arr[i] = arr[i].Replace("play", "123");
}
}
var res = string.Join(" ", arr);
File.WriteAllText(@"c:\File1.txt", result);
Also, this is case sensitive make sure this is what you want.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With