Java

Java的indexof函数有哪些使用技巧

小樊
81
2024-09-30 00:43:18
栏目: 编程语言

在Java中,indexOf函数是String类的一个重要方法,用于查找指定字符或子字符串在字符串中首次出现的位置。以下是一些使用indexOf函数的技巧:

  1. 基本用法
String str = "Hello, World!";
int index = str.indexOf("World");
System.out.println(index);  // 输出7
  1. 从指定位置开始查找
String str = "Hello, World! World!";
int index = str.indexOf("World", 8);  // 从第8个位置开始查找
System.out.println(index);  // 输出19
  1. 查找子字符串
String str = "Hello, World!";
int index = str.indexOf("World");
System.out.println(index);  // 输出7
  1. 不区分大小写
String str = "Hello, World!";
int index = str.toLowerCase().indexOf("WORLD");
System.out.println(index);  // 输出7
  1. 查找多个子字符串
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
  1. 使用负数参数
String str = "Hello, World!";
int index = str.indexOf("World", -1);  // 从字符串末尾开始向前查找
System.out.println(index);  // 输出7
  1. 未找到子字符串时的返回值
String str = "Hello, World!";
int index = str.indexOf("Java");
System.out.println(index);  // 输出-1,因为"Java"不在字符串中
  1. 链式调用
String str = "Hello, World!";
int index = str.toLowerCase().indexOf("world", 8);
System.out.println(index);  // 输出19

这些技巧可以帮助你更有效地使用Java中的indexOf函数。

0
看了该问题的人还看了