Page 1 of 1

Bug in "removing a substring using string substitution"

Posted: 05 Apr 2011 09:25
by ghostmachine4
Source: Remove - Remove a substring using string substitution

Code tested: WinXP

Code: Select all

C:\work>type test.bat
@echo off
set str=the cat in the hat soothe my heart
echo.%str%
set str=%str:the =%
echo.%str%

C:\work>test.bat
the cat in the hat soothe my heart
cat in hat soomy heart


The code is supposed to remove all occurrences of "the" from the string, but fails to cater for words such as "soothe" (which is not "the" ), "breathe", "blithe" etc.

Its better to split the sentence/text using tokens (ie, delimited by spaces). An implementation in vbscript

Code: Select all

s = Split( WScript.Arguments(0) )
For i=0 To UBound(s)
   If LCase(s(i)) <> "the" Then
      WScript.StdOut.Write s(i) & " "
   End If
Next


Note: vbscript comes installed by default on most Windows distribution. There is no reason one could not get to know it and harness its capabilities (same with powershell).

Example test

Code: Select all

C:\work>cscript //nologo test1.vbs "the cat in the hat soothe my heart"
cat in hat soothe my heart



Now, the exact word "the" are removed. Of course, another method is to use regular expression where the engine can check for boundaries , (normally with \b modifier), but that's another story.

Also note that it caters for case-insensitivity, so "the" or "The" , "THe" are removed. The Batch version does not cater for that.


DosItNotHelp

Re: Bug in "removing a substring using string substitution"

Posted: 06 Apr 2011 00:09
by DosItHelp
Yes - the command interpreter allows for simple string substitution not necessarily word substitution.
You think this example doesn't get the point across? If someone want's to propose a better example for string substitution then I would consider it for inclusion.

Note: vbscript comes installed by default on most Windows distribution. There is no reason one could not get to know it and harness its capabilities (same with powershell).

Agree. I think the dostips site attracts mainly users that don't have the choice or will to switch away from Batch. Some users may not even know vbscript but know some batch and want a batch solution. So to solve a tricky problem within a batch that's easily solved in vbscript, a pure vbscript may just not help them. What may help is an extensible vbscript function library embedded into a batch function so that the vbs functions can be called from within the batch and the results be received in environment variables. Well I guess this is a separate Topic...