-
Notifications
You must be signed in to change notification settings - Fork 0
Example: String length
rbaltrusch edited this page Feb 14, 2021
·
4 revisions
The home page directly greets any wiki visitors with this unusual and slightly cryptic piece of batch code to determine the length of a string:
1 set "string=hello world"
2 echo %string%>temp.txt
3 for /f %%f in ("temp.txt") do ( set /a length=%%~zf - 2 )
4 del temp.txt
5 echo length of string is %length%
added line numbers for reference
But what actually happens here?
- In line 1, we declare a variable called string and set it to the string value hello world. Note the missing whitespace around the assignment operator ( = ): no whitespace can be used before the assignment operator. Whitespace after the operator would be incorporated into the string. Also note the quotation marks around the entire assignment: this is required when assigning a string that contains spaces.
- In line 2, we print out the value of variable string (wrapping the variable in percent signs for variable expansion), but redirect the output destination from the console to a new file called temp.txt. Again, notice the missing whitespace around the redirection operator ( > ), which would otherwise be interpreted to be part of the string.
- In line 3, we use the /f switch for loop, which loops through the file contents of the file "temp.txt" and stores each line in the for-loop variable %%f. On each iteration of the for loop (in this case, only one, as the file contains a single line), we declare a variable called length and set it to %%~zf and subtract 2 from it. The expression %%~zf takes the for-loop variable %%f and modifies it using the in-fix ~z, which stands for the file size of %%f in bytes. Two bytes need to be subtracted from that file size, as they are automatically included in the file by Windows. Note the /a switch of the set command, which needs to be used to allow arithmetic operations on a variable.
- Finally, we delete the no longer required tempfile on line 4 and print out the length of the string to the console.