2024年5月11日发(作者:)

字符串indexof(s)的用法

在Java中,indexOf() 是 String 类的一个方法,用于查找一个字符串在另一

个字符串中首次出现的位置。如果未找到该字符串,则返回 -1。

下面是 indexOf() 方法的几种用法:

1. 基本用法:

java

String str = "Hello, World!";

int index = f("World"); // 返回 7

2. 使用开始索引:

你可以指定从哪个索引位置开始搜索。例如,从第7个字符开始搜索:

java

int startIndex = 6;

int index = f("World", startIndex); // 返回 7

3. 查找子字符串:

如果你想查找一个子字符串在另一个字符串中的位置,可以使

用 indexOf() 方法。例如:

java

String str = "Hello, World!";

int index = f("World"); // 返回 7

4. 查找字符:

你还可以使用 indexOf() 方法查找单个字符在字符串中的位置:

java

String str = "Hello, World!";

int index = f('o'); // 返回 4

5. 查找多次出现的位置:

如果你想查找一个字符串在另一个字符串中所有出现的位置,可以使用

循环和 indexOf() 方法。例如:

java

String str = "Hello, World! World is beautiful.";

int firstIndex = f("World"); // 返回 7

int secondIndex = f("World", firstIndex + 1); // 返回 19

注意,每次调用 indexOf() 后,下一次搜索将从上次结束的位置开始,因此

需要手动更新开始搜索的位置。