ExcelBanter

ExcelBanter (https://www.excelbanter.com/)
-   Excel Programming (https://www.excelbanter.com/excel-programming/)
-   -   Fast string replacement (https://www.excelbanter.com/excel-programming/450746-fast-string-replacement.html)

Robert Crandal[_3_]

Fast string replacement
 
I have the following sample string:
(My actual strings are much longer than this)

s = "You must eat lots of fruits and vegetables every day
in the daytime hours."

I'm looking for a fast way to replace an entire set of words
in the above string as follows:

"must" - "should"
"fruits" - "eggs"
"vegetables" - "bacon"
"day" - "morning"

The final output should be:

"You should eat lots of eggs and bacon every morning
in the daytime hours."

The string replacements must occur on word boundaries
only. So, if "daytime" occurs in the string, then I do not
want to change that to "morningtime".

The faster the solution, the better. Would a regular
expression approach be faster than using a "for-each"
construct with a bunch of boolean logic and Instr() calls?






GS[_2_]

Fast string replacement
 
Given you want word boundaries only, your list of words should include
the character following the word...

Function ReplaceWords$(sText$, sWords$)
Dim sz$, vTmp, v1, n&

v1 = Split(sWords, ","): sz = sText

For n = LBound(v1) To UBound(v1)
vTmp = Split(v1(n), ":")
sz = Replace(sz, vTmp(0), vTmp(1))
Next 'n
ReplaceWords = sz
End Function

Sub Test_ReplaceWords()
Const sWords$ = "must :should ,fruits :eggs ,vegetables :bacon ,day
:morning "
Const sText$ = "You must eat lots of fruits and vegetables every day
in the daytime hours."
Debug.Print ReplaceWords(sText, sWords)
End Sub

--
Garry

Free usenet access at http://www.eternal-september.org
Classic VB Users Regroup!
comp.lang.basic.visual.misc
microsoft.public.vb.general.discussion



GS[_2_]

Fast string replacement
 
Reposting test routine because it didn't post right 1st time...


Sub Test_ReplaceWords()
Const sWords$ = "must :should ,fruits :eggs ," _
& "vegetables :bacon ,day :morning "
Const sText$ = "You must eat lots of fruits and vegetables every day
in the daytime hours."
Debug.Print ReplaceWords(sText, sWords)
End Sub

--
Garry

Free usenet access at http://www.eternal-september.org
Classic VB Users Regroup!
comp.lang.basic.visual.misc
microsoft.public.vb.general.discussion




All times are GMT +1. The time now is 09:17 AM.

Powered by vBulletin® Copyright ©2000 - 2025, Jelsoft Enterprises Ltd.
ExcelBanter.com