I know how to do this when the variable is pre-defined. However, when asking for the user to enter in some kind of input, how do I trim leading and trailing whitespace? This is what I have so far:
@echo off set /p input=: echo. The input is %input% before ::trim left whitespace for /f "tokens=* delims= " %%a in ("%input%") do set input=%%a ::trim right whitespace (up to 100 spaces at the end) for /l %%a in (1,1,100) do if "!input:~-1!"==" " set input=!input:~0,-1! echo. The input is %input% after pause
To remove leading and trailing spaces in Java, use the trim() method. This method returns a copy of this string with leading and trailing white space removed, or this string if it has no leading or trailing white space.
strip(): returns a new string after removing any leading and trailing whitespaces including tabs (\t). rstrip(): returns a new string with trailing whitespace removed.
You can use the STRIP function to remove both the leading and trailing spaces from the character strings.
If you only want to remove leading or trailing whitespace use lstrip() or rstrip() respectively.
The solution below works very well for me.
Only 4 lines and works with most (all?) characters.
:Trim SetLocal EnableDelayedExpansion set Params=%* for /f "tokens=1*" %%a in ("!Params!") do EndLocal & set %1=%%b exit /b
@echo off call :Test1 & call :Test2 & call :Test3 & exit /b :Trim SetLocal EnableDelayedExpansion set Params=%* for /f "tokens=1*" %%a in ("!Params!") do EndLocal & set %1=%%b exit /b :Test1 set Value= a b c set Expected=a b c call :Trim Actual %Value% if "%Expected%" == "%Actual%" (echo Test1 passed) else (echo Test1 failed) exit /b :Test2 SetLocal EnableDelayedExpansion set Value= a \ / : * ? " ' < > | ` ~ @ # $ [ ] & ( ) + - _ = z set Expected=a \ / : * ? " ' < > | ` ~ @ # $ [ ] & ( ) + - _ = z call :Trim Actual !Value! if !Expected! == !Actual! (echo Test2 passed) else (echo Test2 failed) exit /b :Test3 set /p Value="Enter string to trim: " %=% echo Before: [%Value%] call :Trim Value %Value% echo After : [%Value%] exit /b
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With