📜  java字符串之-indexof()(1)

📅  最后修改于: 2023-12-03 14:43:00.596000             🧑  作者: Mango

Java字符串之 indexOf()

在Java中,字符串是一种非常常用的数据类型。Java中的字符串是引用类型,由Java标准库提供支持。其中,indexOf()方法是一个常用的字符串处理方法,它用于在一个字符串中查找指定的字符或子字符串,并返回其位置。

语法

indexOf()方法的语法如下:

public int indexOf(int ch)
public int indexOf(int ch, int fromIndex)
public int indexOf(String str)
public int indexOf(String str, int fromIndex)

其中,ch是要查找的字符,str是要查找的子字符串。fromIndex是指在哪个索引开始查找,如果不指定,默认从索引0开始查找。

返回值

indexOf()方法返回一个整数类型的结果,表示查找到的字符或子字符串在原字符串中的位置。如果未找到,返回-1。

使用示例

以下是一些使用indexOf()方法的示例:

  • 查找单个字符:
String str = "Hello World";
int index = str.indexOf('o');
System.out.println(index);  // 输出4
  • 查找子字符串:
String str = "Hello World";
int index = str.indexOf("World");
System.out.println(index);  // 输出6
  • 指定开始查找位置:
String str = "Hello World";
int index = str.indexOf('o', 5);  // 从索引5开始查找
System.out.println(index);  // 输出7
String str = "Hello World";
int index = str.indexOf("World", 3);  // 从索引3开始查找
System.out.println(index);  // 输出-1,未找到
  • 没有找到对应的字符或子字符串:
String str = "Hello World";
int index = str.indexOf('s');
System.out.println(index);  // 输出-1,未找到
注意事项
  • indexOf()方法返回的是第一次出现的位置,如果有多个匹配项,则只返回第一个匹配项的位置。
String str = "Hello World";
int index = str.indexOf('l');
System.out.println(index);  // 输出2
  • indexOf()方法区分大小写,如果要忽略大小写,可以使用indexOfIgnoreCase()方法。
String str = "Hello World";
int index = str.indexOf("world");
System.out.println(index);  // 输出-1,未找到

index = str.indexOfIgnoreCase("world");
System.out.println(index);  // 输出6
  • indexOf()方法还可以用于判断一个字符串中是否包含某个字符或子字符串。
String str = "Hello World";
if (str.indexOf('o') != -1) {
    System.out.println("包含'o'字符");
}

if (str.indexOf("World") != -1) {
    System.out.println("包含'World'子字符串");
}

以上就是indexOf()方法的介绍及使用示例。在实际开发中,它是一种非常常用的字符串处理方法,掌握它对于编写高效的字符串处理代码非常重要。