Follow on Facebook

Like and Share on Facebook

Sunday, January 25, 2015

Java String indexOf


Java String indexOf

The java string indexOf() method 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

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

Expected Output:
2 8
5
3

No comments:

Post a Comment