温馨提示×

java怎么获取某个字符的所有位置

小亿
117
2023-10-14 03:20:59
栏目: 编程语言

在Java中,可以使用indexOf方法来获取某个字符在字符串中的位置。该方法返回指定字符在字符串中第一次出现的位置,如果不存在则返回-1。如果想获取所有出现的位置,则可以使用一个循环来反复调用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中的位置。

输出结果:

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

另外,如果想获取所有出现的位置,也可以使用正则表达式来实现。使用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中的位置。

输出结果:

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

0