String indexOf() Method in Java with EXAMPLE

What is Java String IndexOf Method?

The indexOf method is used to get the integer value of a particular index of String type object, based on criteria specified in the parameters of the IndexOf method.
A common scenario can be when a system admin wants to find the index of the '@' character of the email Id of a client and then wants to get the remaining substring. In that situation, IndexOf method can be used.
Syntax
The syntax of this Java method is:
public int indexOf(int cha)
Parameters
cha − a character.
Return Value
This Java method returns the index within this string of the first occurrence of the specified character. It returns -1 if the character does not occur.
The Java String IndexOf method has four overloads. All the overloads return an integer type value, representing the returned index. These overloads differ in the type and number of parameters they accept.
IndexOf(char b)
This method returns the index of the character 'b' passed as parameter. If that character is not available in the string, the returned index would be -1.
IndexOf(char c, int startindex)
The given method would return the index of the first occurrence of character 'c' after the integer index passed as second parameter "startindex." All the occurrences of character 'c' before the "startindex" integer index would be ignored.
IndexOf(String substring)
The above method returns the index of the first character of the substring passed as a parameter to it. If that substring is not available in the string, the returned index would be -1.
IndexOf(String substring, int startindex)
This Java method returns the index of the first character in the substring passed as the first parameter, after the "startindex" index value. If substring starts from the passed integer value of "startindex", that substring would be ignored.
Example
public class Sample_String {
    public static void main(String args[]) {

        String str_Sample = "This is Index of Example";
        //Character at position
        System.out.println("Index of character 'x': " + str_Sample.indexOf('x'));
        //Character at position after given index value
        System.out.println("Index of character 's' after 3 index: " + str_Sample.indexOf('s', 3));
        //Give index position for the given substring
        System.out.println("Index of substring 'is': " + str_Sample.indexOf("is"));
        //Give index position for the given substring and start index
        System.out.println("Index of substring 'is' form index:" + str_Sample.indexOf("is", 5));
    }
}
Output:
Index of character 'x': 12
Index of character 's' after 3 index: 3
Index of substring 'is': 2
Index of substring 'is' form index:5

No comments:

Post a Comment