How to print a substring of a given String using Java substring() method
Coding River
How To Print The Substring Of A Given String Based On The Specified Indexes You Will Pass As Parameters using Java substring() method
In this video, we will discuss on the Java substring() method. I will show you how to use this method in order to get the substring of a given String based on the indexes you will pass as parameters. So, in this video, I will use an example to show you how to use this substring() method.
But before that, there are two points I would like you to note
Point number 1 is that the substring() method can take either one or two parameters of type integer and it returns a String value whenever it is evaluated
Point number 2 is that, there are actually two ways to use this method. • The first way is to use this method by passing only one parameter representing the starting index • The second way is to use this method by passing both the starting index and the end index
- Let me walk you through the first example explaining the first way to use this method by passing only one parameter which represents the starting index
String str = “Programming” System.out.println(str.substring(4));
If we run this program, the result in the console will be : ramming
Because the statement str.substring(4) will return the substring out of our str String, starting from the character positioned at specified index 4 up to the last character of the String.
Note here that if the starting index that you specify must not be less than zero or greater than the length of the String. Or else the method will throw an exception
- Now, let me walk you through the second example in order to show you how to use the substring() method by passing both the starting index position and the end index of the substring you want to return.
String str = “Programming”; System.out.println(str.substring(2 , 5);
When we run this program, the result in the console will be : ogr
What has happened is that the method has returned a substring of our str String. And that substring begins from the character positioned at the specified starting index 2 up to the character positioned at the specified end index 4 (not index 5 but 4).
We can note here that the starting index is always inclusive and the end index is exclusive. Also, the method will throw an exception if the starting index is less than zero or if the starting index is greater than the end index or if the end index is greater than the length of the String.
That was it concerning the substring() method, I hope this video has been informative and please don’t forget to support this channel by liking this video and also by Subscribing to this channel.
Let’s meet in the next video, take care !!!!
#codingriver #java #programming ... https://www.youtube.com/watch?v=1q7mARlmmpY
15227137 Bytes