如何按 Java 中的字符拆分字符串?

How do I split a String by Characters in Java?

我用不同的正则表达式尝试了很多次,但 none 似乎有效。基本上,我有一个 StringTokenizer 当前正在按空格拆分字符串,但我希望它按每个字符拆分。我当前的代码:

FileReader fr = new FileReader("test.txt");
BufferedReader br = new BufferedReader(fr);
StringTokenizer st = new StringTokenizer(br.readLine());
char c = reader.next().charAt(0);

这会在索引零处获取字符串的字符。字符串从索引零开始。另外,另一种选择是

for (int i = 0; i < numberOfChars; ++i){
    // get the character using charAt(i)
    // store the character using an array, as others have specified
}

记得用new Scanner(BufferedReader(FileReader("test.txt")));

有关详细信息,请阅读 Take a char input from the Scanner

I have a StringTokenizer that is currently splitting the string by spaces,

阅读 StringTokenizer API。如果您不指定分隔符,则使用默认分隔符。

所以你需要指定所有的分隔符。

或者,更简单的方法是只使用 String.toCharArray() 方法并遍历数组。

如果您需要它们作为字符:

char[] characters = br.readLine().toCharArray();

如果您需要它们作为字符串:

String[] characters = br.readLine().split("");