Tuesday, 19 July 2016

Searching within a String using indexOf(), lastIndexOf() and contains() methods

There are scenarios when you want to find characters or substrings within a string. For that purpose String class provides accessor methods that return the position within the string of a specific character or substring: indexOf() and lastIndexOf().

  • indexOf() - This method search forward from the beginning of the string and returns the index within this string of the first occurrence of the specified character/substring. If a character or substring is not found indexOf() returns -1.
  • lastIndexOf() - This method search backward from the end of the string and returns the index within this string of the last occurrence of the specified character/substring. If a character or substring is not found lastIndexOf() returns -1.

The String class also provides a search method, contains, that returns true if the string contains a particular character sequence. Use this method when you only need to know that the string contains a character sequence, but the precise location isn't important.

indexOf() and lastIndexOf()

There are various overloaded versions of indexOf() and lastIndexOf() methods.

indexOf()

  • indexOf(int ch) - Returns the index within this string of the first occurrence of the specified character.
  • indexOf(int ch, int fromIndex) - Returns the index within this string of the first occurrence of the specified character, starting the search at the specified index.
  • indexOf(String str) - Returns the index within this string of the first occurrence of the specified substring.
  • indexOf(String str, int fromIndex) - Returns the index within this string of the first occurrence of the specified substring, starting at the specified index.

lastIndexOf()

  • lastIndexOf(int ch) - Returns the index within this string of the last occurrence of the specified character.
  • lastIndexOf(int ch, int fromIndex) - Returns the index within this string of the last occurrence of the specified character, searching backward starting at the specified index.
  • lastIndexOf(String str) - Returns the index within this string of the last occurrence of the specified substring.
  • lastIndexOf(String str, int fromIndex) - Returns the index within this string of the last occurrence of the specified substring, searching backward starting at the specified index.

Examples of using indexOf() and lastIndexOf()

  1. If you get date as String in the dd/mm/yyyy format and you want to get the first index of char '/'.
    public class StringSearch {
    
     public static void main(String[] args) {
      String date = "12/01/2016";
      System.out.println("index " + date.indexOf('/'));
     }
    
    }
    

    Output

    index 2
    
  2. Using the same date string if you want to get the month part of it.
    public class StringSearch {
    
     public static void main(String[] args) {
      String date = "12/01/2016";
      System.out.println("index " + date.indexOf('/'));
      String month = date.substring(0, date.indexOf('/'));
      System.out.println("month " + month);
     }
    }
    

    Output

    index 2
    month 12
    
  3. Using the same date string if you want to get the year part then you can use lastIndexOf() method.
    public class StringSearch {
    
     public static void main(String[] args) {
      String date = "12/01/2016";
      System.out.println("index " + date.lastIndexOf('/'));
      String year = date.substring(date.lastIndexOf('/') + 1);
      System.out.println("year " + year);
     }
    }
    

    Output

    index 5
    year 2016
    
  4. If you get some string in the format “xx/xx/xx” and you want the middle substring.
    public class StringSearch {
    
     public static void main(String[] args) {
      String path = "home/index/test.html";
      
      String str = path.substring(path.indexOf('/') + 1, path.lastIndexOf('/'));
      System.out.println("str - " + str);
    
     }
    
    }
    

    Output

    str - index
    

contains() method

public boolean contains(CharSequence s) - Returns true if and only if this string contains the specified sequence of char values. Otherwise it returns false.

Example code

public class StringSearch {

 public static void main(String[] args) {
  String str1 = "Contains example";
  String str2 = "example";
  System.out.println("str1 contains str2 " + str1.contains(str2));
 }
}

Output

str1 contains str2 true

Here note that str2 which is passed as an argument in contains() method is a string not CharSequence, so string can be used in place of CharSequence. It is possible because CharSequence is an interface which is implemented by String.

If you want to use contains() method ignoring case then you can convert both strings to upper or lowercase while searching.

As example – In previous program if str2 is changed to “Example” then contains will return false.

public class StringSearch {
 public static void main(String[] args) {
  String str1 = "Contains example";
  String str2 = "Example";
  System.out.println("str1 contains str2 " + str1.contains(str2));
 }
}

Output

str1 contains str2 false

Now, if you want to ignore case then you can change both to lower case.

public class StringSearch {

 public static void main(String[] args) {
  String str1 = "Contains example";
  String str2 = "Example";
  System.out.println("str1 contains str2 " + str1.toLowerCase().contains(str2.toLowerCase()));
 }

}
str1 contains str2 true

It won't change the original strings as strings are immutable and using methods like toLowerCase will create a new string.

That's all for this topic Searching within a String using indexOf(), lastIndexOf() and contains() methods. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related topics

  1. String in Java
  2. String comparison in Java
  3. String charAt() and subString() methods in Java
  4. How to reverse a string in Java
  5. How to add double quotes to a String
  6. Java String interview questions

You may also like -

>>>Go to Java Basics page

No comments:

Post a Comment