阅读量:73
在Java中,indexOf函数是String类的一个重要方法,用于查找指定字符或子字符串在字符串中首次出现的位置。以下是一些使用indexOf函数的技巧:
- 基本用法:
String str = "Hello, World!";
int index = str.indexOf("World");
System.out.println(index); // 输出7
- 从指定位置开始查找:
String str = "Hello, World! World!";
int index = str.indexOf("World", 8); // 从第8个位置开始查找
System.out.println(index); // 输出19
- 查找子字符串:
String str = "Hello, World!";
int index = str.indexOf("World");
System.out.println(index); // 输出7
- 不区分大小写:
String str = "Hello, World!";
int index = str.toLowerCase().indexOf("WORLD");
System.out.println(index); // 输出7
- 查找多个子字符串:
String str = "Hello, World! World!";
int index1 = str.indexOf("World");
int index2 = str.indexOf("World", index1 + 5); // 在第一个"World"之后5个位置开始查找
System.out.println(index1); // 输出7
System.out.println(index2); // 输出19
- 使用负数参数:
String str = "Hello, World!";
int index = str.indexOf("World", -1); // 从字符串末尾开始向前查找
System.out.println(index); // 输出7
- 未找到子字符串时的返回值:
String str = "Hello, World!";
int index = str.indexOf("Java");
System.out.println(index); // 输出-1,因为"Java"不在字符串中
- 链式调用:
String str = "Hello, World!";
int index = str.toLowerCase().indexOf("world", 8);
System.out.println(index); // 输出19
这些技巧可以帮助你更有效地使用Java中的indexOf函数。