共計 794 個字符,預計需要花費 2 分鐘才能閱讀完成。
在 Java 中,可以使用字符串類的 indexOf()方法來查找指定字符在字符串中的位置。
例如,下面的代碼示例演示了如何查找字符串中第一個出現的指定字符的位置:
String str = "Hello, World!";
char ch = 'o';
int index = str.indexOf(ch);
if (index != -1) {System.out.println("Character '" + ch + "' found at index " + index);
} else {System.out.println("Character '" + ch + "' not found in the string.");
}
在上面的示例中,我們定義了一個字符串 str
和一個字符 ch
,然后使用indexOf()
方法來查找字符 ch
在字符串 str
中第一次出現的位置。如果找到了指定字符,就會返回該字符在字符串中的索引位置,否則返回 -1。
除了使用字符作為參數,indexOf()
方法還可以接受字符串作為參數,用來查找字符串中第一次出現的子字符串的位置。
String str = "Hello, World!";
String substr = "World";
int index = str.indexOf(substr);
if (index != -1) {System.out.println("Substring '" + substr + "' found at index " + index);
} else {System.out.println("Substring '" + substr + "' not found in the string.");
}
上面的示例演示了如何查找字符串中第一次出現的子字符串的位置。如果找到了子字符串,就會返回該子字符串在字符串中的索引位置,否則返回 -1。
丸趣 TV 網 – 提供最優質的資源集合!
正文完