javastringindexof

来源:undefined 2025-03-05 09:20:42 1017

Java中的String.indexOf()方法是用来查找某个字符或子字符串在字符串中*次出现的位置的。它返回一个整数值,表示该字符或子字符串从0开始的索引位置。如果没有找到该字符或子字符串,则返回-1。

String indexOf(char ch):

该方法接受一个参数ch,表示要查找的字符。它会在字符串中寻找*个出现的ch,并返回该字符在字符串中的索引位置。例如:

```java

String str = "Hello

World!";

int index = str.indexOf(o);

System.out.println("Index of o: " + index);

```

上述代码会输出:Index of o: 4,表示字符o在字符串"Hello

World!"中的*个出现位置的索引是4。

String indexOf(String str):

该方法接受一个参数str,表示要查找的子字符串。它会在字符串中寻找*个出现的str,并返回该子字符串在字符串中的索引位置。例如:

```java

String str = "Hello

World!";

int index = str.indexOf("World");

System.out.println("Index of World: " + index);

```

上述代码会输出:Index of World: 7,表示子字符串"World"在字符串"Hello

World!"中的*个出现位置的索引是7。

String indexOf(char ch

int fromIndex):

该方法接受两个参数,*个参数ch表示要查找的字符,第二个参数fromIndex表示开始查找的索引位置。它会从指定的索引位置开始寻找字符ch,并返回该字符在字符串中的索引位置。例如:

```java

String str = "Hello

World!";

int index = str.indexOf(o

5);

System.out.println("Index of o after index 5: " + index);

```

上述代码会输出:Index of o after index 5: 7,表示字符o在从索引位置5开始的子字符串"o

World!"中的*个出现位置的索引是7。

String indexOf(String str

int fromIndex):

该方法接受两个参数,*个参数str表示要查找的子字符串,第二个参数fromIndex表示开始查找的索引位置。它会从指定的索引位置开始寻找子字符串str,并返回该子字符串在字符串中的索引位置。例如:

```java

String str = "Hello

World!";

int index = str.indexOf("World"

5);

System.out.println("Index of World after index 5: " + index);

```

上述代码会输出:Index of World after index 5: 7,表示子字符串"World"在从索引位置5开始的子字符串"

World!"中的*个出现位置的索引是7。

如果要在字符串中查找所有出现的字符或子字符串,可以使用一个循环来多次调用indexOf()方法,将上一次调用的结果作为下一次调用的fromIndex参数。例如:

```java

String str = "Hello

World!";

int index = 0;

while (index != -1) {

index = str.indexOf(o

index);

if (index != -1) {

System.out.println("Found o at index: " + index);

index++;

}

}

```

上述代码会输出:Found o at index: 4 和 Found o at index: 7,表示字符o在字符串"Hello

World!"中的*个和第二个出现位置的索引分别是4和7。

总结:

String.indexOf()方法可用于查找字符或子字符串在字符串中*次出现的位置。它有多个重载形式,可以根据参数的不同进行使用。如果要查找所有出现的字符或子字符串,需要使用循环结合indexOf()方法来实现。

上一篇:c 输出 下一篇:gouint

最新文章