溫馨提示×

java怎么獲取某個字符的所有位置

小億
183
2023-10-14 03:20:59
欄目: 編程語言

在Java中,可以使用indexOf方法來獲取某個字符在字符串中的位置。該方法返回指定字符在字符串中第一次出現(xiàn)的位置,如果不存在則返回-1。如果想獲取所有出現(xiàn)的位置,則可以使用一個循環(huán)來反復調(diào)用indexOf方法,每次從上一個位置的后面開始搜索,直到找不到為止。

下面是一個示例代碼:

public class Main {
public static void main(String[] args) {
String str = "Hello World";
char ch = 'o';
int index = str.indexOf(ch);
while (index != -1) {
System.out.println("字符 " + ch + " 在位置 " + index);
index = str.indexOf(ch, index + 1);
}
}
}

以上代碼會輸出所有字符o在字符串Hello World中的位置。

輸出結(jié)果:

字符 o 在位置 4
字符 o 在位置 7

另外,如果想獲取所有出現(xiàn)的位置,也可以使用正則表達式來實現(xiàn)。使用PatternMatcher類可以方便地進行正則匹配。以下是一個使用正則表達式來獲取所有字符位置的示例代碼:

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
String str = "Hello World";
char ch = 'o';
Pattern pattern = Pattern.compile(String.valueOf(ch));
Matcher matcher = pattern.matcher(str);
while (matcher.find()) {
System.out.println("字符 " + ch + " 在位置 " + matcher.start());
}
}
}

以上代碼會輸出所有字符o在字符串Hello World中的位置。

輸出結(jié)果:

字符 o 在位置 4
字符 o 在位置 7

0