Replace_String_Word

Replace String Function using Word$
uncleBen has already shown you how to use InStr to replace a string.

The example below uses the Word$ function to do the same.

1210894571

code format="vbnet" 'Replace Sting Function

'replace a word Original$ = "The quick brown fox jumps over the lazy dog" print Original$ print ReplaceString$(Original$, "fox", "chicken") print

'replace a phrase Original$ = "The tree is on my knee, there is a bird on my knee" print Original$ print ReplaceString$(Original$, "my knee", "his head") print

'replace a letter Original$ = "kikerikiiiiiii" print Original$ print ReplaceString$(Original$, "i", "o") print

'replace a token Original$ = "Line 1\nLine 2\nLine 3\n\n" CRLF$ = chr$(13);chr$(10) print Original$ print ReplaceString$(Original$, "\n", CRLF$)

'replace a letter that is not found Original$ = "kikerikiiiiiii" print Original$ print ReplaceString$(Original$, "a", "o") end

function ReplaceString$(Source$, Expression$, Replacement$) 'Replace any string by another '   'Source$ ........ string to search in   'Expression$ .... string to search for 'Replacement$ ... string to use instead do       index = index + 1 FirstPart$ = word$(Source$, index, Expression$) NextPart$ = word$(Source$, index + 1, Expression$)

if FirstPart$ = Expression$ then ReplaceString$ = ReplaceString$; Replacement$ else if NextPart$ = "" and instr(Source$, Expression$, len(ReplaceString$)) = 0 then ReplaceString$ = ReplaceString$; FirstPart$ else ReplaceString$ = ReplaceString$; FirstPart$; Replacement$ end if       end if    loop until NextPart$ = "" end function code