4

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?

5 Answers 5

13

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

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

2

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?

Comments

0

Try changing it to

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

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

1 Comment

you would also lose the spaces on either side of the word with this answer - the regex answer below is better, but if you use this approach, be sure to replace " play " with " 123 ", not with "123".
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.