Java indexof() method: returns the index position of the first occurrence

Grammar 1

indexOf(int ch)

Example

String strCom = "I like java";
int index = strCom.indexOf(5);

Grammar 2

indexOf(int ch,int fromIndex)

Note: there is no limit to the value of fromindex. If it is negative, it has the same effect as if it were 0: the entire string is searched. If it is greater than the length of this string, it has the same effect as if it is equal to the length of this string: Return - 1.

Example

String strCom="I like java";
int index=strCom.indexOf(7,0);

Grammar 3

public int indexOf(String str)

Example

String strCom="C语言中文网!";
int index=strCom.indexOf("C语言中文网");

Grammar 4

public int indexOf(String str,int fromIndex)

Typical application

Using indexof method to query string is very convenient. This method is also widely used in development. This example uses the indexof method to query the index position of the character a in the string. The code is as follows:

public static void main(String[] args){
    String str = "We are students";  //定义字符串对象
    int index = str.indexOf("a");  //使用indexOf方法查询字符a在字符串中的索引位置
    System.out.println("a在"+str+"中的位置是:"+index);  //输出索引位置
}

Running result: the position of a in we are students is: 3

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>