Java indexof函数怎么使用
Java中的indexOf函数用于查找指定字符或字符串在字符串中第一次出现的位置。它有两种形式的用法:
int indexOf(int ch)
:返回指定字符在字符串中第一次出现的位置。如果未找到指定字符,则返回-1。
示例代码:
String str = "Hello World";
int index = str.indexOf('o');
System.out.println(index); // 输出:4
int indexOf(String str)
:返回指定字符串在字符串中第一次出现的位置。如果未找到指定字符串,则返回-1。
示例代码:
String str = "Hello World";
int index = str.indexOf("lo");
System.out.println(index); // 输出:3
此外,indexOf函数还有两种带有起始位置参数的使用方式:
int indexOf(int ch, int fromIndex)
:从指定的起始位置开始,返回指定字符在字符串中第一次出现的位置。如果未找到指定字符,则返回-1。
示例代码:
String str = "Hello World";
int index = str.indexOf('o', 5);
System.out.println(index); // 输出:7
int indexOf(String str, int fromIndex)
:从指定的起始位置开始,返回指定字符串在字符串中第一次出现的位置。如果未找到指定字符串,则返回-1。
示例代码:
String str = "Hello World";
int index = str.indexOf("lo", 2);
System.out.println(index); // 输出:3
版权声明
本文仅代表作者观点,不代表米安网络立场。
发表评论:
◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。