Substring Contains String

May 3, 2013 | Java General
In C/C++, string is an array of characters with a terminating /0. But in Java, the scenario is completely different. In Java, string exists as a class String from java.lang package. To make string manipulation easy, Designers introduced many methods in String class with different functionality. Of them two are given substring() and contains() in this tutorial Substring Contains String.

Before going into example, let us see method signatures as defined in String class. Both are overloaded with different parameters.

  1. String substring(int indexNum): Returns a string containing all the characters existing from indexNum to the end in the given string.
  2. String substring(int indexNum1, int indexNum2): Returns a string containing all the characters existing from indexNum1 to indexNum2-1 in the given string.
  3. boolean contains(String str): Checks whether a string exists in another string. Returns boolean value of str exists in the original string.
Following is an example on Substring Contains String
public class Demo
{
  public static void main(String args[])
  {
    String originalString = "ABCDEFGHIJKL";
    String givenString = "EFG";
    boolean b1 = originalString.contains(givenString);
    System.out.println("ABCDEFGHIJKL contains EFG: " + b1);   // prints true
    System.out.println("ABCDEFGHIJKL contains EG: " + "ABCDEFGHIJKL".contains("EG")); // can be done like this also. Prints false

    String str1 = originalString.substring(4);                // returns a string from 4th character to last; prints EFGHIJKL
    String str2 = originalString.substring(2, 6);             // returns a string of 2, 3, 4, 5; prints CDEF
    System.out.println("\noriginalString.substring(4): " + str1);  
    System.out.println("originalString.substring(2, 6): " + str2);
  }
}

Substring ContainsOutput Screenshot on Substring Contains String

Methods are self-explanatory. Let us write a practical example.

public class Demo
{
  public static void main(String args[])
  {
    String mails[] = { "jyostna@gmail.com", "jyothi@yahoo.com", "srinvas@hotmailcom" };

    System.out.println("Names are:\n");
    for(int i = 0; i < mails.length; i++)
    {
      int index = mails[i].indexOf('@');
      String str = mails[i].substring(0, index);
      System.out.println(str);
    }
  }
}

Substring ContainsOutput Screenshot on Substring Contains Java