ValoChele

ValoChele

  • NA
  • 68
  • 21k

How to add numbers to string in a file?

Dec 21 2017 11:16 AM
I have a text file called sample.txt and its contents look like
 
John Howard Carpenter @#@ born in Carthage, New York, 
to mother Milton Jean (Carter) and father Howard Ralph Carpenter.
His family moved to Bowling @#@, Kentucky, @#@ his father, a professor,
was @#@ of the music @#@ at Western Kentucky University.
 
How do I replace all @#@ by the numbers starting from 1, then incremented by +1 till no @#@ is left in the file.
 
I've tried
  1. string x=File.ReadAllText(@"C:sample.txt");  
  2. string y="@#@";  
  3. int i=1;  
  4. MatchCollection matches = Regex.Matches(x, y, RegexOptions.IgnoreCase);  
  5. if (matches.Count>0)  
  6.             {  
  7.                 foreach (Match m in matches) {  
  8.                     string n=x.Replace(y,i.ToString());  
  9.                     i++;  
  10.                     File.WriteAllText(y,n);  
  11.                 }  
  12.             }  
  13. MessageBox.Show("Done");  
It does not do anything
BTW: The expected output is
 
John Howard Carpenter 1 born in Carthage, New York, to mother Milton Jean (Carter) and father Howard Ralph Carpenter. His family moved to Bowling 2, Kentucky, 3 his father, a professor, was 4 of the music 5 at Western Kentucky University.  

Answers (4)