For Programmers: Free Programming Magazines  


Home > Archive > Visual Basic Syntax > November 2005 > replace multiple strings









You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

 

Author replace multiple strings
chieko

2005-11-21, 7:03 pm

Hello,
I'm having trouble writing the code to replace three different strings in a
small text file.
I want to replace all occurances of: sugar, candy; flour, pillsbury; and
cornstarch, armandhammer with sugar candy; flour pillsbury; cornstarch
armandhammer.
I can use the replace code for one variable only using
replace$(fbuf, replaceString, ReplaceWithString)
s #fnum, 1
Put #fnum, 1
that will only replace one of the sets of values. How can i find all 3
different search terms and replace them without opening and closing the text
file multiple times?

Thanks,
Chieko
Rick Rothstein [MVP - Visual Basic]

2005-11-21, 7:03 pm

> I'm having trouble writing the code to replace three different
strings in a
> small text file.
> I want to replace all occurances of: sugar, candy; flour, pillsbury;

and
> cornstarch, armandhammer with sugar candy; flour pillsbury;

cornstarch
> armandhammer.
> I can use the replace code for one variable only using
> replace$(fbuf, replaceString, ReplaceWithString)
> s #fnum, 1
> Put #fnum, 1
> that will only replace one of the sets of values. How can i find all

3
> different search terms and replace them without opening and closing

the text
> file multiple times?


Give this code a try...

Dim FileNum As Long
Dim TotalFile As String
' Read in the entire file all at once
FileNum = FreeFile
Open "c:\SomeDircectory\YourFile.txt" For Binary As #FileNum
TotalFile = Space(LOF(FileNum))
Get #FileNum, , TotalFile
Close #FileNum
' Perform your individual replacements
TotalFile = Replace(TotalFile, replaceString1, WithString1)
TotalFile = Replace(TotalFile, replaceString2, WithString2)
TotalFile = Replace(TotalFile, replaceString3, WithString3)
' Now save the entire file back out replacing the old one
FileNum = FreeFile
Open "c:\SomeDircectory\YourFile.txt" For Output As #FileNum
Print #FileNum, TotalFile
Close #FileNum

Rick


Sponsored Links







Also available: Server administration forum archive | Web Design forum archive | Software forum archive | Hardware reviews archive

Copyright 2008 codecomments.com