Open In App

Batch Script – Right String

Last Updated : 04 Jan, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we are going to learn how to use the concept of Right String using Batch Script.

Right String uses the concept of negative indexing. We have to extract the characters using :~ followed by the negative index of the character from which we want to print a substring from the main string. Using the right string we can print characters from the right side of any given string.

Batch Script :

@echo off 
set str=Geeks for Geeks
echo %str% 

set str=%str:~-5% 
echo %str%

pause

Using the above code we are going to print a substring from -5 to -1 index from the given string(i.e. Geeks for Geeks).

Explanation:

  • By using ‘ set ‘ we are getting input of any string
  • In the next line using ‘ echo %str% ‘ we are printing our string.
  • Now in the next line using indexing we are going to eliminate characters from the right end. When we are taking the index from the right side, it starts from “-1” and increases by 1 as we move further from right to left.
  • General representation – set str=%string:~right index% . For example, If we are giving the right index as -5, so the string from ‘-5’ to ‘-1’ will be printed.
  • Then we are using ‘pause’, to hold the screen until any key is pressed, so that we can read our output.

Another Approach :

Batch Script :

@echo off 
set str=GFG is best platform for Geeks
echo %str% 

:: 10 characters from right will be printed
set str=%str:~-10%  
echo %str%

pause

In this example, we have given the index value as ‘-10’ which means a substring having 10 characters from the right side will be extracted and printed.

Output:

As we can clearly see that a substring of 10 characters from the right is printed as output.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads