Monday, March 21, 2022

Java String Search 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 in Java provides accessor methods that return the position within the string of a specific character or substring: indexOf() and lastIndexOf().

  • indexOf()- This method searches 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 searches 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() methods in String

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

Java indexOf() method

  • 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.

Java lastIndexOf() method

  • 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.

Searching for character in a String using indexOf() and lastIndexOf() methods

  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
    

Searching for substring in a String using indexOf() and lastIndexOf() methods

Same way you can also use indexOf() and lastIndexOf() methods to search for a substring within a given string.

public class StringSearch {
  public static void main(String[] args) {
    String str = "This is a test String to test searching in String";
    System.out.println("First occurrence of String test is at index- "
             + str.indexOf("test"));
    System.out.println("Last occurrence of String test is at index- " 
             + str.lastIndexOf("test"));
    System.out.println("Content between fist and last occurrence of test in the String- " 
             + str.substring(str.indexOf("test"), str.lastIndexOf("test")));
     
    System.out.println("First occurrence of String test after index 15- " 
             + str.indexOf("test", 15));
  }
}

Output

First occurrence of String test is at index- 10
Last occurrence of String test is at index- 25
Content between fist and last occurrence of test in the String- test String to 
First occurrence of String test after index 15- 25

Searching in String using 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.

Java contains() method example

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.

For 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 Java String Search Using indexOf(), lastIndexOf() And contains() Methods. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Basics Tutorial Page


Related topics

  1. String Comparison in Java equals(), compareTo(), startsWith() Methods
  2. Java String substring() Method - Getting Substring
  3. Is String Thread Safe in Java
  4. Splitting a String Using split() Method in Java
  5. Java String Interview Questions And Answers

You may also like-

  1. Find All Permutations of a Given String Java Program
  2. equals() And hashCode() Methods in Java
  3. Fail-Fast Vs Fail-Safe Iterator in Java
  4. Method Reference in Java
  5. Abstraction in Java
  6. Difference Between equals() Method And equality Operator == in Java
  7. static Block in Java
  8. Difference Between component-scan And annotation-config in Spring

1 comment: