java中的indexof方法怎么用

   2025-02-13 8360
核心提示:Java中的indexOf方法用于查找指定字符或子字符串在字符串中第一次出现的位置。它的使用方法如下:indexOf(int ch):查找指定字符

Java中的indexOf方法用于查找指定字符或子字符串在字符串中第一次出现的位置。

它的使用方法如下:

indexOf(int ch):查找指定字符ch在字符串中第一次出现的位置。

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

indexOf(int ch, int fromIndex):从指定索引fromIndex开始,查找指定字符ch在字符串中第一次出现的位置。

String str = "Hello World";int index = str.indexOf('o', 5);System.out.println(index); // 输出7

indexOf(String str):查找指定子字符串str在字符串中第一次出现的位置。

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

indexOf(String str, int fromIndex):从指定索引fromIndex开始,查找指定子字符串str在字符串中第一次出现的位置。

String str = "Hello World";int index = str.indexOf("lo", 5);System.out.println(index); // 输出-1,表示未找到

需要注意的是,如果未找到指定字符或子字符串,indexOf方法会返回-1。如果要判断字符串中是否包含指定字符或子字符串,可以根据返回值是否为-1来进行判断。

 
 
更多>同类维修知识
推荐图文
推荐维修知识
点击排行
网站首页  |  关于我们  |  联系方式  |  用户协议  |  隐私政策  |  网站留言