Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to replace a single word in text file?

Status
Not open for further replies.

ridifvx

Programmer
Apr 10, 2003
34
ID
HI..i really need your help
I have a single file call a.txt its contains many word "what" Now i want to make an apps which will change all the word "what" into the word "who" and save it into the same file..please

of course it's not a homework..:) because i will do some analogic with a complex one using a simple case above..
Thanks indeed..
 
Solution 1:
-open a.txt
-load it in a StringBuilder object e.g. sb = new StringBuilder(); by reading one byte at the time
-close a.txt
- replace all occurences e.g. sb.Replace("what","who');
- now send the sb object to the a.txt by overriding it.
Use FileStream , ReadByte, WriteByte
Example:
StringBuilder sb= new StringBuilder();
string txtfile="a.txt";
Stream fileStream = new FileStream(assemblyPath + txtfile, FileMode.Open, FileAccess.Read, FileShare.None);
int read = -1;
while (true)
{
read = fileStream.ReadByte();
if (read == -1)
break;
sb.Append(read);
}

sb.Replace("what","who");
fileStream.Close();
fileStream = null;
Stream fileStream = new FileStream(assemblyPath + txtfile, FileMode.Create, FileAccess.Write, FileShare.None);
string buff = sb.ToString();
for (int i=0;i<buff.Length;i++)
{
fileStream.WriteByte(Convert.ToByte(buff));
}
fileStream.Close();

Solution 2:

-open a.txt for read (use StreamReader)
-open a.out for output (use StreamWriter )
-for each line read from a.txt
-replace &quot;what&quot; with &quot;who&quot; in this line and send it in a.out using a StreamWriter object
-close the both files
-if all Okay then copy a.out to a.txt e.g.
File.Copy(&quot;a.out&quot;,&quot;a.txt&quot;);

Solution 3:
Use MemoryStream to load the a.txt and do the same steps as described in the solution 1.
etc...
-obislavu-


 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top