How to get a SubString of a String in Java
This is a tutorial in which we are going to create a program that gets substring of a string in java. We all know that a substring is a part of a sentence or a string. Java String class provides substring method with some overloaded parameter.
So, now let's start this tutorial!
1. Open JCreator or NetBeans and make a java program with a file name of subString.java.
2. Import java.lang package because in this library, substring class is there. Import also javax.swing hence we will use JOptionPane.showInputDialog for inputting and JOptionPane.showMessageDialog for displaying the output.
- import java.lang.*;
- import javax.swing.*;
3. In your main, initialize string sentence variable as your input using the JOptionPane.showInputDialog.
Now, we will create again a variable named part as string. Here, we will get the substring of index 2 to our inputted sentence. The first substring method with single parameter startIndex will take some part of the string from the starting index until the last character in the string.
- String part = sentence.substring(2);
Then, we will create again a substring method. The second substring method take two parameters, startIndex and lastIndex. This method returns the substring start from startIndex to the lastIndex.
- part = sentence.substring(12, 21);
To display the output:
4. Now, input a sentence to our program like the image below.
Press F5 and run the program.
Hope this helps! :)
Engr. Lyndon Bermoy
IT Instructor/System Developer/Android Developer/Freelance Programmer
If you have some queries, feel free to contact the number or e-mail below.
Add and Follow me on Facebook: https://www.facebook.com/donzzsky
Visit and like my page on Facebook at: https://www.facebook.com/BermzISware