Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# replace string in a text file

Tags:

c#

replace

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?

like image 658
Quan Avatar asked Dec 05 '22 08:12

Quan


2 Answers

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

like image 135
Sriram Sakthivel Avatar answered Dec 29 '22 23:12

Sriram Sakthivel


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.

like image 27
serene Avatar answered Dec 29 '22 23:12

serene