Java indexof函数怎么使用

499
2023/7/14 14:32:48
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

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

  1. int indexOf(int ch):返回指定字符在字符串中第一次出现的位置。如果未找到指定字符,则返回-1。

示例代码:

String str = "Hello World";
int index = str.indexOf('o');
System.out.println(index);  // 输出:4
  1. int indexOf(String str):返回指定字符串在字符串中第一次出现的位置。如果未找到指定字符串,则返回-1。

示例代码:

String str = "Hello World";
int index = str.indexOf("lo");
System.out.println(index);  // 输出:3

此外,indexOf函数还有两种带有起始位置参数的使用方式:

  1. int indexOf(int ch, int fromIndex):从指定的起始位置开始,返回指定字符在字符串中第一次出现的位置。如果未找到指定字符,则返回-1。

示例代码:

String str = "Hello World";
int index = str.indexOf('o', 5);
System.out.println(index);  // 输出:7
  1. int indexOf(String str, int fromIndex):从指定的起始位置开始,返回指定字符串在字符串中第一次出现的位置。如果未找到指定字符串,则返回-1。

示例代码:

String str = "Hello World";
int index = str.indexOf("lo", 2);
System.out.println(index);  // 输出:3

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: 实现java定时器的方式有哪些