Padraic Cunningham
Padraic Cunningham

Reputation: 180391

how to replace multiple occurrences of a substring in C#

I am just starting to learn C# and I am trying to replace all occurrences of a certain substring in a text file with a \ if the text is not separated by whitespace or not . What is the easiest way to do this? Thanks.

Upvotes: 0

Views: 3515

Answers (2)

Civa
Civa

Reputation: 2176

if you wanna use Regex

Simple and single statement

File.WriteAllText("c:\\test.txt", Regex.Replace(File.ReadAllText("c:\\test.txt"), @"\bBACKS\b", "\\"));

Upvotes: 1

MUG4N
MUG4N

Reputation: 19717

  1. read in your file:

    var fileContents = System.IO.File.ReadAllText(@"C:\YourFile.txt");
    
  2. replace text:

    fileContents = fileContents.Replace("BACKS", "\\"); 
    
  3. write the file to filesystem:

    System.IO.File.WriteAllText(@"C:\YourFile.txt", fileContents);
    

Upvotes: 10

Related Questions