JavaDevNotes.com

Java Substring Examples

The substring method of String is very useful in Core Java Programming. It is a fundamental method in performing String manipulation. What it does is extract a sequence of characters from a String and return that as a new String object. This post will show examples on how to use the Java substring method.

Description

The Java String's substring method has two variants. The first one takes only one argument, while the other takes two arguments.

  • substring(int beginIndex)

    This method will return a new String object containing the substring of the given string from the specified startIndex (inclusive). This will get the portion of a String beginning from the given beginIndex and upto the last character of the String.

    Syntax
    public String substring(int beginIndex)
    

    Where

    • beginIndex - the index where to begin extracting the returned substring(inclusive)
  • The key idea is that it will get all the characters from the index specified by beginIndex upto the last character in the String. For example, if we have the String "ABCDE", the character at index 2 is the "C". Hence, "ABCDE".substring(2) will return all the characters from "C" to "E", which is the String "CDE".

    Example

    Here are more examples on how to use Java substring.

    public class SubstringTest {
       public static void main(String[] args) {
          String testString = "ABCDEFGHIJ";
          System.out.println(testString.substring(0));
          System.out.println(testString.substring(1));
          System.out.println(testString.substring(2));
          System.out.println(testString.substring(3));
          System.out.println(testString.substring(4));
          System.out.println(testString.substring(5));
          System.out.println(testString.substring(6));
          System.out.println(testString.substring(7));
          System.out.println(testString.substring(8));
          System.out.println(testString.substring(9));
       }
    }
    

    And here is the sample output of the code above.

    ABCDEFGHIJ
    BCDEFGHIJ
    CDEFGHIJ
    DEFGHIJ
    EFGHIJ
    FGHIJ
    GHIJ
    HIJ
    IJ
    J
    

  • substring(int beginIndex, int endIndex)

    This method will return a new String object containing the substring of the given string from specified startIndex to endIndex. This will get the portion of a String beginning from the given beginIndex and upto the specified endIndex.

    Syntax
    public String substring(int beginIndex, int endIndex)
    

    Where

    • beginIndex - the index where to begin extracting the returned substring.(inclusive)
    • endIndex - the index where to end extracting the returned substring. (exclusive)

    The key idea is that we can specify where to start and end copying characters from the source String. Remember also that the beginIndex is inclusive while the endIndex is exclusive. For example, the character at index 2 of the String "ABCDE" is "C", while the character at index 4 is "E". The returned String will have the characters from "C" inclusive upto character "E" exclusive (meaning we don't include E). The result is "CD".

    Example

    Here are more examples on how to use Java substring.
    public class SubstringTest {  
       public static void main(String[] args) {
          String testString = "ABCDEFGHIJ";
          System.out.println(testString.substring(0,5));
          System.out.println(testString.substring(1,5));
          System.out.println(testString.substring(2,5));
          System.out.println(testString.substring(0,6));
          System.out.println(testString.substring(1,6));
          System.out.println(testString.substring(2,6));
          System.out.println(testString.substring(0,7));
          System.out.println(testString.substring(1,7));
          System.out.println(testString.substring(2,7));
       }
    }
    
    And here is the sample output of the code above.
    ABCDE
    BCDE
    CDE
    ABCDEF
    BCDEF
    CDEF
    ABCDEFG
    BCDEFG
    CDEFG
    

Other Samples

Here are some programming problems where substring can be useful.

  • Print All Possible Substring of a String

    Here is a sample program that will accept a String and prints all it's possible substrings.

    import java.util.Scanner;
    public class PrintAllSubstring {  
       public static void main(String[] args) {
          System.out.println("Enter a string:");
          Scanner in = new Scanner(System.in);
          String inputString = in.nextLine();
          for (int beginIndex = 0; beginIndex < inputString.length(); beginIndex++) {
             for (int endIndex = beginIndex + 1; endIndex <= inputString.length(); endIndex++) {
                System.out.println(inputString.substring(beginIndex, endIndex));
             }
          }
       }
    }
    

    And here is the output assuming the String wxyz was entered.

    Enter a string:
    wxyz
    w
    wx
    wxy
    wxyz
    x
    xy
    xyz
    y
    yz
    z
    
  • Find Middle String

    Here is an example on how to get the middle of a String by using the substring method in the algorithm.

    public class MiddleStrTest {
       public static void main(String[] args) {
          System.out.println("A       --> " + getMiddleString("A"));
          System.out.println("AB      --> " + getMiddleString("AB"));
          System.out.println("ABC     --> " + getMiddleString("ABC"));
          System.out.println("ABCD    --> " + getMiddleString("ABCD"));
          System.out.println("ABCDE   --> " + getMiddleString("ABCDE"));
          System.out.println("ABCDEF  --> " + getMiddleString("ABCDEF"));
          System.out.println("ABCDEFG --> " + getMiddleString("ABCDEFG"));
       }
       private static String getMiddleString(String str) {
          if (str.length() <= 2) {
             return str;
          }
          int beginIndex = (str.length() - 1) / 2;
          int endIndex = beginIndex + 2 - (str.length() % 2);
          return str.substring(beginIndex, endIndex);
       }
    }
    

    Here is the sample output:

    A       --> A
    AB      --> AB
    ABC     --> B
    ABCD    --> BC
    ABCDE   --> C
    ABCDEF  --> CD
    ABCDEFG --> D
    

  • Reverse a String

    Here is an example program that will reverse a String using Java substring method.

    public class ReverseTest {
       public static void main(String[] args) {
          System.out.println(reverse("ABCDEFG"));
       }
       private static String reverse(String str) {
          if (str.length() <= 1) {
             return str;
          }
          return reverse(str.substring(1)) + str.substring(0, 1);
       }
    }
    

    This will output the reverse of the String ABCDEFG, which is:

    GFEDCBA
    
  • Test Palindrome

    Here is an example program that will test if a String is a palindrome or not. It utilizes the Java substring method as much as possible.

    public class PalTest {
       public static void main(String[] args) {
          System.out.println(palindrome("ABCBA"));
          System.out.println(palindrome("ABCCBA"));
          System.out.println(palindrome("ABCCXA"));
          System.out.println(palindrome("ABCDEFG"));
       }
       private static boolean palindrome(String str) {
          if (str.length() <= 1) {
             return true;
          }
          String first = str.substring(0, 1);
          String last = str.substring(str.length() - 1);
          return first.equals(last)
                && palindrome(str.substring(1, str.length() - 1));
       }
    }
    

    This is the output of the palindrome test

    true
    true
    false
    false