java中的indexof方法
时间: 2023-09-11 17:04:17 浏览: 77
Java中的indexOf方法是用来查找一个字符串中指定字符或子串第一次出现的位置的方法。该方法的语法如下:
```
public int indexOf(String str)
```
其中,str是要查找的字符串或字符,该方法返回值是一个int类型的整数,表示查找到的字符或子串在原字符串中第一次出现的位置,如果没有找到则返回-1。
例如,下面的代码演示了如何使用indexOf方法查找一个字符串中指定字符的位置:
```
String str = "hello world";
int index = str.indexOf('o');
System.out.println(index); // 输出:4
```
该代码中,我们定义了一个字符串"hello world",然后使用indexOf方法查找字符'o'在该字符串中的位置,最后将结果4输出。
相关问题
java中indexof方法的用法
Java中indexof方法是用于查找字符或子字符串在字符串中第一次出现的位置。它的语法如下:
int index = str.indexOf(searchStr);
其中,str是要查找的主字符串,searchStr是要查找的字符或子字符串。
如果找到了匹配的字符或子字符串,返回它在主字符串中的索引位置。如果没有找到匹配项,则返回-1。
java的indexof方法
Java中的indexOf()方法用于查找指定字符或字符串在字符串中第一次出现的位置。它的语法如下:
```
public int indexOf(int ch)
public int indexOf(String str)
public int indexOf(int ch, int fromIndex)
public int indexOf(String str, int fromIndex)
```
其中,ch是要查找的字符,str是要查找的字符串,fromIndex是开始查找的位置。
例如,下面的代码演示了如何使用indexOf()方法查找一个字符串中某个子串的位置:
```
String str = "Hello, world!";
int index = str.indexOf("world");
System.out.println("The index of 'world' in the string is: " + index);
```
输出结果为:
```
The index of 'world' in the string is: 7
```
在这个例子中,我们调用了indexOf()方法来查找字符串中"world"这个子串的位置,它返回了7,表示这个子串在字符串中的位置是从第7个字符开始的。