我用来分割任意数量空白字符串的代码是
String out="SELECT * FROM EMP WHERE EMPID=10";
String array[] = out.split("\\s+");
我希望将“out”字符串中的空格包含在array []对象中,同时使用空格分割。 我想要的输出是:
array[]={"SELECT","[WHITE SPACE]","*","[WHITE SPACE]","FROM","[WHITE SPACE]","EMP","[WHITE SPACE]","WHERE","[WHITE SPACE]","EMPID=10"}
但我得到的输出是:
array[]={"SELECT","*","FROM","EMP","WHERE","EMPID=10"}
任何帮助将不胜感激
答案 0 :(得分:5)
由于split
接受正则表达式,您可以使用lookarounds:
out.split("(?<=\\s)|(?=\\s)");
这将输出:
[SELECT, , *, , FROM, , EMP, , WHERE, , EMPID=10]
请注意,分隔符(在您的情况下为空格)包含在结果中。
答案 1 :(得分:3)
尝试将其拆分为:
String array[] = out.split("(?=\\s)",-1);
代码是:
public static void main(String[] args) {
String out="SELECT * FROM EMP WHERE EMPID=10";
String array[] = out.split("(?=\\s)",-1);
for (String string : array) {
System.out.print(string);
}
}
输出:
SELECT * FROM EMP WHERE EMPID=10
答案 2 :(得分:2)