溫馨提示×

Java indexof的用法有哪些

小億
96
2023-08-01 10:11:51
欄目: 編程語言

Java中的indexOf方法用于查找指定字符或字符串在字符串中第一次出現(xiàn)的位置,并返回索引值。

使用方法:

  1. indexOf(char ch):返回指定字符在字符串中第一次出現(xiàn)的位置,如果不存在返回-1。

示例:

String str = "Hello, world!";
int index = str.indexOf('o');
System.out.println(index); // 輸出4
  1. indexOf(String str):返回指定字符串在字符串中第一次出現(xiàn)的位置,如果不存在返回-1。

示例:

String str = "Hello, world!";
int index = str.indexOf("world");
System.out.println(index); // 輸出7
  1. indexOf(char ch, int fromIndex):返回指定字符在字符串中從指定位置開始到末尾第一次出現(xiàn)的位置,如果不存在返回-1。

示例:

String str = "Hello, world!";
int index = str.indexOf('o', 5);
System.out.println(index); // 輸出7
  1. indexOf(String str, int fromIndex):返回指定字符串在字符串中從指定位置開始到末尾第一次出現(xiàn)的位置,如果不存在返回-1。

示例:

String str = "Hello, world!";
int index = str.indexOf("o", 5);
System.out.println(index); // 輸出7

0