c# replace string in a text file

2019-06-28 03:26发布

问题:

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?

回答1:

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



回答2:

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.



回答3:

An alternative approach, and not regex based could be the following:

Define a few extension methods:

static class Exts
{
    public static string GetLettersAndDigits(this string source)
    {
        return source.Where(char.IsLetterOrDigit)
            .Aggregate(new StringBuilder(), (acc, x) => acc.Append(x))
            .ToString();
    }

    public static string ReplaceWord(this string source, string word, string newWord)
    {
        return String.Join(" ", source
            .Split(new string[] { " " }, StringSplitOptions.None)
            .Select(x =>
            {
                var w = x.GetLettersAndDigits();
                return w == word ? x.Replace(w, newWord) : x;
            }));
    }
}

Usage:

var input = File.ReadAllText(@"C:\test.txt");
var output = input.ReplaceWord("play", "123");

Console.WriteLine(input);
Console.WriteLine(output);

Prints:

This is a test: display play, play display -play !play - maybe it's working?

This is a test: display 123, 123 display -123 !123 - maybe it's working?



回答4:

Try changing it to

text.Replace(" play ","123");

but this way it won't replace something like play. play, play;



回答5:

Another technique you can use in this situation is to add more recognizable tokens into the text you wish to edit.. for example:

bla bla {PLAY} bla bla PLAY bla bla

would become

bla bla 123 bla bla PLAY bla bla


标签: c# replace