Home »
Java programming language
Java String indexOf(int ch, int fromIndex) Method with Example
Java String indexOf(int ch, int fromIndex) Method: Here, we are going to learn about the indexOf(int ch, int fromIndex) method with example in Java.
Submitted by IncludeHelp, on February 20, 2019
String indexOf(int ch, int fromIndex) Method
indexOf(int ch, int fromIndex) is a String method in Java and it is used to get the index of a specified character in the string from given fromIndex. That means to search for the character will start from the given index (fromIndex).
If the character exists in the string from fromIndex, it returns the index of the first occurrence of the character, if the character does not exist in the string, it returns -1.
Syntax:
int str_object.indexOf(int ch, int fromIndex);
Here,
- str_object is an object of main string in which we have to find the index of given character.
- chr is a character to be found in the string.
- fromIndex is the position in main string from where we method will start the searching for the character.
It accepts a character, from index and returns an index of its first occurrence or -1 if the character does not exist in the string.
Example:
Input:
String str = "IncludeHelp"
Function call:
str.indexOf('H', 4)
Output:
7
Input:
String str = "IncludeHelp"
Function call:
str.indexOf('W', 2)
Output:
-1
Java code to demonstrate the example of String.indexOf() method
public class Main
{
public static void main(String[] args) {
String str = "IncludeHelp";
char ch;
int index;
ch = 'H';
index = str.indexOf(ch, 4);
if(index != -1)
System.out.println(ch + " is found at " + index + " position.");
else
System.out.println(ch + " does not found.");
ch = 'e';
index = str.indexOf(ch, 3);
if(index != -1)
System.out.println(ch + " is found at " + index + " position.");
else
System.out.println(ch + " does not found.");
ch = 'W';
index = str.indexOf(ch, 2);
if(index != -1)
System.out.println(ch + " is found at " + index + " position.");
else
System.out.println(ch + " does not found.");
}
}
Output
H is found at 7 position.
e is found at 6 position.
W does not found.