Java string substring() method explained
Types of substring() method
- public String substring(int beginIndex) {}
- public String substring(int beginIndex, int endIndex) {}
Imp.note: The method substring() takes the argument in this way substring(inclusive, exclusive) which means the starting index is taken while the last index isn't taken the index=endIndex-1 is actually taken to print the string (hope it is clear)
1. substring(int beginIndex): It will just take the string from starting index and returns the string from this index till the end, let's see how to implement it in the code-
Example 01 of substring(int beginIndex) function
public class Substring {
public static void main(String[] args)
{
String s1 = "Sparrow";
System.out.println(s1.substring(2));//arrow printed
}
}
public class Substring {
public static void main(String[] args)
{
String s1 = "Sparrow";
System.out.println(s1.substring(2));//arrow printed
}
}
arrow
here, as you give the starting index 2 then at 2nd index of string the value which is there is taken for example here, "a" is there, so it takes the string from "a" till the end and return "arrow" simply.
2. substring(int beginIndex, int endIndex): It will just take the string from starting index till the endIndex as given by the user which is exclusive (endIndex-1 is actually taken) and returns the resulted string, let's see how to implement it in the code-
Example 01 of substring(int beginIndex, int endIndex) function
public class Substring {
public static void main(String[] args)
{
String s1 = "Sparrow";
System.out.println(s1.substring(2,5));//arr will be printed
}
}
arr
here, in this example as you see the index (2,5) matches with (inclusive index, exclusive index) so the string taken from index 2 till the index 4 as we discussed the second last index is actually taken to output the string because it is exclusive.
Hello, visitor your comments are so helpful for us so do not hesitate just write the comment we read all your comments so don't think your comment goes waste.