BATCH_ Trim String
My first solution I came up with involved substring replacement including a helper string added before and after the real string. This works as long as that helper string does not appear anywhere in the original string.
:: Trims whitespace at beginning and end of a string. :: PARAM :: 1 string to trim :: RETURN String trimmed string :TRIM SETLOCAL ENABLEEXTENSIONS ENABLEDELAYEDEXPANSION SET HLPSTR=#####%RANDOM%##### SET STR="!HLPSTR!%~1!HLPSTR!"& SET STR=!STR:~1,-1! :TRIM_INNER_LOOP IF "!STR:%HLPSTR% =%HLPSTR%!" NEQ "!STR!" ( SET STR="!STR:%HLPSTR% =%HLPSTR%!"& SET STR=!STR:~1,-1! GOTO :TRIM_INNER_LOOP ) ELSE IF "!STR: %HLPSTR%=%HLPSTR%!" NEQ "!STR!" ( SET STR="!STR: %HLPSTR%=%HLPSTR%!"& SET STR=!STR:~1,-1! GOTO :TRIM_INNER_LOOP ) SET STR="!STR:%HLPSTR%=!"& SET STR=!STR:~1,-1! ENDLOCAL & SET RESULT="%STR%"& SET RESULT=!RESULT:~1,-1! GOTO :EOFSo after thinking about that for a while (~10 seconds), it came to my mind that I do have a way to retrieve the first or the last character of a string. So this solution followed:
:: Trims whitespace at beginning and end of a string. :: PARAM :: 1 string to trim :: RETURN String trimmed string :TRIM SETLOCAL ENABLEEXTENSIONS ENABLEDELAYEDEXPANSION SET STR="%~1"& SET STR=!STR:~1,-1! :TRIM_INNER_LOOP IF "!STR!" NEQ "" ( IF "!STR:~0,1!" == " " ( SET STR=!STR:~1! ) ELSE IF "!STR:0,1!" == " " ( SET STR=!STR:~1! ) ELSE IF "!STR:~-1!" == " " ( SET STR=!STR:~0,-1! ) ELSE IF "!STR:~-1!" == " " ( SET STR=!STR:~0,-1! ) ELSE ( GOTO :TRIM_INNER_LOOP_END ) GOTO :TRIM_INNER_LOOP ) :TRIM_INNER_LOOP_END ENDLOCAL & SET RESULT="%STR%"& SET RESULT=!RESULT:~1,-1! GOTO :EOFWhat you cannot see: I compare against space and then against tab. But I disliked the horrible IF-ELSE comparison stuff and ended with replacement check against a whitespace-string:
:: Trims whitespace at beginning and end of a string. :: PARAM :: 1 string to trim :: RETURN String trimmed string :TRIM SETLOCAL ENABLEEXTENSIONS ENABLEDELAYEDEXPANSION SET STR="%~1"& SET STR=!STR:~1,-1! :: whitespace is space and tab SET WHITESPACE= :TRIM_INNER_LOOP IF "!STR!" NEQ "" ( IF "!WHITESPACE:%STR:~0,1%=!" NEQ "!WHITESPACE!" ( SET STR=!STR:~1! GOTO :TRIM_INNER_LOOP ) ELSE IF "!WHITESPACE:%STR:~-1%=!" NEQ "!WHITESPACE!" ( SET STR=!STR:~0,-1! GOTO :TRIM_INNER_LOOP ) ) ENDLOCAL & SET RESULT="%STR%"& SET RESULT=!RESULT:~1,-1! GOTO :EOF
cypressor - 30. Nov, 19:15
Small bug
This is because the Endlocal statement reverts Delayed Expansion to the state is was in before the SetLocal statement that enabled it in the TRIM routine. If it was disabled before calling TRIM, the delayed expansion of !RESULT:~1,-1! doesn't happen, and that is seen as a text string, not a variable.