Get String Length using Windows Batch


Under Linux, there is a famous quote: “When there is a shell, there is a way.”, meaning that the Linux SHELL script is very powerful and in fact can do almost anything within or beyond your imagination. The Windows batch programming (with file extensions *.cmd or *.bat), on the other hand, is also capable of general tasks, however, some tricks might be required because there are sometimes no straightforward solutions. In this sense, the Linux SHELL is more powerful for example, the windows batch programming does not neither provide a straightforward switch/case nor a while statement. However, these can be emulated by multiple if-s and goto statements since the basic programming flows are combined by selection (if-s) and loops (goto-s).

The following is a batch script that demonstrates the C-like strlen function. It parses each parameter (using shift until no more command line parameters are available) and prints the lengths of each one.

@echo off
:: strlen.bat
:: https://uploadbeta.com

if [%1] EQU [] goto end

:loop
	if [%1] EQU [] goto end
	set _len=0
	set _str=%1
	set _subs=%_str%

	:getlen		
		if not defined _subs goto result
		:: remove first letter until empty
		set _subs=%_subs:~1%
		set /a _len+=1
		goto getlen

	:result
		echo strlen("%1")=%_len%		
		shift
		goto loop
:end

The idea is to remove each time the first character of the string and increment the length counter until the string is empty. The output example is given below.

strlen Get String Length using Windows Batch algorithms batch script beginner code code library implementation programming languages string tricks windows windows command shell

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
308 words
Last Post: Batch Programming Revisited, Chess Board Printing
Next Post: Print Big Characters using Windows Batch Programming

The Permanent URL is: Get String Length using Windows Batch

Leave a Reply