How to get a SubString of a String in Java
Submitted by donbermoy on Tuesday, May 27, 2014 - 21:20.
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.
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.
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.
To display the output:
4. Now, input a sentence to our program like the image below.
Press F5 and run the program.
Output:
Hope this helps! :)
Best Regards,
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.
Mobile: 09488225971
Landline: 826-9296
E-mail:[email protected]
Add and Follow me on Facebook: https://www.facebook.com/donzzsky
Visit and like my page on Facebook at: https://www.facebook.com/BermzISware
- import java.lang.*;
- import javax.swing.*;
- String sentence;
- part = sentence.substring(12, 21);
Add new comment
- 291 views