新闻

新闻动态

良好的口碑是企业发展的动力

javastringindexof

发布时间:2024-01-31 08:20:22 点击量:92
泉州网站建设价格

 

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

免责声明:本文内容由互联网用户自发贡献自行上传,本网站不拥有所有权,也不承认相关法律责任。如果您发现本社区中有涉嫌抄袭的内容,请发送邮件至:dm@cn86.cn进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。本站原创内容未经允许不得转载。
上一篇: gouint
下一篇: pythoncallable