anilak

Text Files Problem 8 Replace Whole Words

Jul 20th, 2013
151
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.00 KB | None | 0 0
  1. //8. Modify the solution of the previous problem to replace only whole words (not substrings).
  2.  
  3. using System;
  4. using System.IO;
  5.  
  6. class ReplaceWordInFile
  7. {
  8.     static void Main()
  9.     {
  10.         using (StreamReader input = new StreamReader("input.txt"))
  11.         {
  12.             using (StreamWriter output = new StreamWriter("output1.txt"))
  13.             {
  14.                 for (string line = input.ReadLine(); line != null; line = input.ReadLine())
  15.                 {
  16.                     for (int index = line.IndexOf("start"); index != -1; index = line.IndexOf("start", index + 1))
  17.                     {
  18.                         if ((index - 1 < 0 || !Char.IsLetter(line[index - 1])) && (index + 5 >= line.Length || !Char.IsLetter(line[index + 5])))
  19.                         {
  20.                             line = line.Insert(index, "finish").Remove(index + 6, 5);
  21.                         }
  22.                     }
  23.                     output.WriteLine(line);
  24.                 }
  25.             }
  26.         }
  27.     }
  28. }
Advertisement
Add Comment
Please, Sign In to add comment