我有一个字符串并尝试将其解析为字符串数组。该字符串看起来像:
c: 00000
u: 00001
h: 0001
r: 0010
s: 0011
e: 010
i: 0110
n: 0111
上面的示例仅涉及一个字符串引用,例如 String str = testClass.toString();
我只想将 0 和 1 放入字符串数组中。
String filtered = str.replaceAll("[^0-1]","");
String[] numbers = filtered.split("\n");
for (String a : numbers) {
System.out.println(a);
}
我编写了上面的代码,但它只给出一行输出。如何解决?
000000000100010010001101001100111
我打算作为
str[0] = "00000";
...
str[7] = "0111"
最佳答案
问题在于,当您调用 str.replaceAll("[^0-1]","")
时,'\n'
也被替换为空字符串。
一种可能的方法是替换除数字之外的所有字符 AND '\n'
:
String filtered = str.replaceAll("[^01\n]","");
String[] list = filtered.split("\n");
另一种方法是直接拆分,只保留 "0"
和 "1"
:
String[] list = str.split("[^01]+");
关于java - 使用换行正则表达式仅拆分字符串整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36580603/