Saturday, 12 September 2015

Java String indexOf

Java String indexOf

The java string indexOf() method returns index of given character value or substring. If it is not found, it returns -1. The index counter starts from zero.

Signature

There are 4 types of indexOf method in java. The signature of indexOf methods are given below:
No.MethodDescription
1int indexOf(int ch)returns index position for the given char value
2int indexOf(int ch, int fromIndex)returns index position for the given char value and from index
3int indexOf(String substring)returns index position for the given substring
4int indexOf(String substring, int fromIndex)returns index position for the given substring and from index

Parameters

ch: char value i.e. a single character e.g. 'a'
fromIndex: index position from where index of the char value or substring is retured
substring: substring to be searched in this string

Returns

index of the string

Java String indexOf() method example

  1. public class IndexOfExample{  
  2. public static void main(String args[]){  
  3. String s1="this is index of example";  
  4. //passing substring  
  5. int index1=s1.indexOf("is");//returns the index of is substring  
  6. int index2=s1.indexOf("index");//returns the index of index substring  
  7. System.out.println(index1+"  "+index2);//2 8  
  8.   
  9. //passing substring with from index  
  10. int index3=s1.indexOf("is",4);//returns the index of is substring after 4th index  
  11. System.out.println(index3);//5 i.e. the index of another is  
  12.   
  13. //passing char value  
  14. int index4=s1.indexOf('s');//returns the index of s char value  
  15. System.out.println(index4);//3  
  16. }}  
Output
2  8
5
3

No comments:

Post a Comment