java indexof方法
时间: 2023-06-02 21:01:38 浏览: 56
Java中的indexOf方法用于查找字符串中特定子字符串的位置。它有两个重载版本:
1. `public int indexOf(String str)`: 返回字符串中第一个出现子字符串str的位置,如果没有找到则返回-1。
2. `public int indexOf(String str, int fromIndex)`: 返回字符串中从fromIndex开始第一个出现子字符串str的位置,如果没有找到则返回-1。
例如:
```java
String str = "Hello World";
int index1 = str.indexOf("o"); // 返回4
int index2 = str.indexOf("o", 5); // 返回7
int index3 = str.indexOf("z"); // 返回-1,因为字符串中没有字符"z"
```
注意,indexOf方法区分大小写,如果需要不区分大小写的查找,可以使用`public int indexOf(String str, int fromIndex)`方法的重载版本。
相关问题
indexof方法java
`indexOf()` 方法是 Java 中用于查找字符串中指定子串的方法之一。它可以返回第一个匹配项的索引,如果没有找到匹配项,则返回 -1。`indexOf()` 方法有两种常用的重载形式,分别是:
1. `indexOf(String str)`:在字符串中查找指定子串,并返回第一个匹配项的索引。
2. `indexOf(String str, int startIndex)`:在字符串中从指定的索引位置开始查找指定子串,并返回第一个匹配项的索引。
以下是两个 `indexOf()` 方法的使用示例:
1. `indexOf(String str)` 方法的使用:
```java
String str = "Hello, world!";
int index = str.indexOf("world");
System.out.println(index); // 输出:7
```
2. `indexOf(String str, int startIndex)` 方法的使用:
```java
String str = "Hello, world!";
int index = str.indexOf("l", 3);
System.out.println(index); // 输出:3
```
在上面的示例中,`indexOf()` 方法从索引位置 3 开始查找字符串中第一个出现的字母 "l",并返回其索引位置。
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个字符开始的。