simple text file question

  • Thread starter Thread starter suzy
  • Start date Start date
S

suzy

hello,

i want to search a text file for an occurrence of a string and replace some
text after the match, then save the file.

eg: if the file is:

<start>
Hello my name is tony, I am 22.
Hello, my name is sonia, I am 18.
Hello, my name is debbie, I am 8.
<end>

I would like to pass in a search string of "I am " and I also want to be
able to increment each of the ages by 1, then save the file.

So the output file would be:

<start>
Hello my name is tony, I am 23.
Hello, my name is sonia, I am 19.
Hello, my name is debbie, I am 9.
<end>

What is the best way to do this?

Many thanks.
 
suzy said:
hello,

i want to search a text file for an occurrence of a string and replace some
text after the match, then save the file.

Load the whole file into a string, and use string.Replace().
eg: if the file is:

<start>
Hello my name is tony, I am 22.
Hello, my name is sonia, I am 18.
Hello, my name is debbie, I am 8.
<end>

I would like to pass in a search string of "I am " and I also want to be
able to increment each of the ages by 1, then save the file.

After loading the file into a string, I guess you could iterate
through the string until you find a digit. Make sure this digit is
preceeded by a *delimiter*. Keep iterating until you find another
*delimiter*. Next, piece together a string starting from the first
digit to the last. Convert this to a number and increment it. Remove
the old number from the string. Insert the new one in the same place.
So the output file would be:

<start>
Hello my name is tony, I am 23.
Hello, my name is sonia, I am 19.
Hello, my name is debbie, I am 9.
<end>

What is the best way to do this?

Many thanks.

Hope that helps.
 
By the way, I should mention that I know I can do a loop with a ReadLine()
iteration, but the text I want to change is likely to be at the end of the
text file with a line preceding it
(contents of that line will be "***DETAILS***").

Is there anyway, I can search from this position onwards rather than start
looping from the top of the file.
 
Why not use FileStream.ReadByte to go through the file looking for "D". When
you find one check for "DETAILS" if its not "DETAILS" then continue with
ReadByte..

G.
 
Truth is, there are many ways to do this. If performance isn't an issue, I
would just read the entire file into a string (I believe StreamReader has a
ReadToEnd method) and then search the string. First you'd do an
IndexOf("***DETAILS***") and then start reading from there, getting the
number between "I am " and "." by using IndexOf and Substring. Then you
could use Convert.ToInt32 to increment. Of course, you could use regular
expressions (maybe some extra points for that) but that would be beyond my
skills.

Chris
 
Back
Top