温馨提示×

java中indexof方法如何使用

小亿
89
2023-11-14 00:22:20
栏目: 编程语言

在Java中,indexOf方法用于查找指定字符或子字符串在字符串中第一次出现的位置。它有两种形式的使用:

  1. 查找指定字符的位置:
String str = "Hello, world!";
int index = str.indexOf('o');
System.out.println(index); // 输出4
  1. 查找指定子字符串的位置:
String str = "Hello, world!";
int index = str.indexOf("world");
System.out.println(index); // 输出7

如果要查找从指定位置开始的第一次出现的位置,可以使用带有第二个参数的indexOf方法:

String str = "Hello, world!";
int index = str.indexOf('o', 5); // 从索引为5的位置开始查找
System.out.println(index); // 输出7

如果要查找最后一次出现的位置,可以使用lastIndexOf方法:

String str = "Hello, world!";
int index = str.lastIndexOf('o');
System.out.println(index); // 输出8

需要注意的是,indexOf方法返回的是字符或子字符串第一次出现的索引,如果找不到指定字符或子字符串,返回-1。

0