Open In App

Batch Script – String length

Improve
Improve
Like Article
Like
Save
Share
Report

In this article , we are going to learn how to find length of any String using Batch Script.

Batch Script :

@echo off
set str=Geeks For Geeks
call :strLen str strlen
echo String is %strlen% characters long
pause
exit /b

:strLen
setlocal enabledelayedexpansion

:strLen_Loop
   if not "!%1:~%len%!"=="" set /A len+=1 & goto :strLen_Loop
(endlocal & set %2=%len%)
goto :eof

In Batch Scripting there no function for checking length of string ,So we will create a function to find length of string.

Explanation :

  • By using ‘ set ‘ we are getting our input string whose length is to calculated.
  • In above code we are creating a Function “strLen” , which we can use to find our string length.
  • From ‘:strLen’ our function is started , then we will initialize our Loop with ‘strLen_Loop’.
  • (“!%1:~%len%!”) this statement is checking that our string is ended or not by using (==””).
if not "!%1:~%len%!"=="" set /A len+=1 & goto :strLen_Loop
  • During execution of our ‘if’ statement its checking if (“!%1:~%len%!”==””) this argument is True then it will Break the Loop and if its False , it will be continued.
  • Now if our argument is False then we will set our ‘len’ variable as ‘len=len+1’ (also written as len+=1).
  • By using ‘goto :strLen_Loop’ we are continuing our Loop.
  • Now , again it will check whether our string is ended or not by using command (“!%1:~%len%!”==””) and increase ‘len’ by 1 if argument is False.
  • Now let’s assume when our argument is True , loop will break and our string length is set in ‘strlen’.
  • When ‘strlen’ is called it will print our string length.

Output:


Last Updated : 04 Jan, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads