Using substring(int) and substring(int,int) in String

There are 2 versions of substring() you should be familiar with. The first is substring(int beginIndex) and the next one is substring(int beginIndex, int endIndex). The first method returns a string starting from the given beginIndex till the end of the string (endIndex=length of string). For example,

"example".substring(1)  returns xample

The next takes the endIndex and works in the following way

"example".substring(0,4) returns exam

Note that the char at endIndex is not included but that at the startIndex is.

class SubstringExample
    public static void main(String args[])
        int startIndex=Integer.parseInt(args[1]);
        int endIndex=Integer.parseInt(args[2]);
        System.out.println("substring("+startIndex+") is "+args[0].substring(startIndex));
        System.out.println("substring("+startIndex+","+endIndex+") is "+args[0].substring(startIndex,endIndex));

Sample Output

java SubstringExample google 0 2

substring(0) is google
substring(0,2) is go

The greatest compliment you can give me is when you share this with others. I sincerely appreciate it :)

Posted by at on

Tags: String Handling,