我们已经准备好了,你呢?

我们与您携手共赢,为您的企业形象保驾护航!

当前位置: 首页 > 问答 > javastringindexof

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()方法来实现。

免责声明:本站内容(文字信息+图片素材)来源于互联网公开数据整理或转载,仅用于学习参考,如有侵权问题,请及时联系本站删除,我们将在5个工作日内处理。联系邮箱:chuangshanghai#qq.com(把#换成@)

我们已经准备好了,你呢?

我们与您携手共赢,为您的企业形象保驾护航!

在线客服
联系方式

热线电话

132-7207-3477

上班时间

周一到周五 09:00-18:00

二维码
线