简体   繁体   English

如何用空格分割字符串并在结果中包含空格作为元素?多个空格分割

[英]How to split string with white spaces and include white spaces as elements in the result?multiple white spaces splitting

The code I used to split the string with any number of white space is 我用来分割任意数量的空格的字符串的代码是

String out="SELECT * FROM EMP WHERE EMPID=10";
String array[] = out.split("\\s+");

I want to include the white spaces in the "out" string into the array[] object while splitting with white spaces. 我希望将“out”字符串中的空格包含到array []对象中,同时使用空格分割。 The output I want is: 我想要的输出是:

array[]={"SELECT","[WHITE SPACE]","*","[WHITE SPACE]","FROM","[WHITE SPACE]","EMP","[WHITE SPACE]","WHERE","[WHITE SPACE]","EMPID=10"}

But the output what I am getting is: 但我得到的输出是:

 array[]={"SELECT","*","FROM","EMP","WHERE","EMPID=10"}

Any help will be appreciated 任何帮助将不胜感激

Since split accepts a regex, you can use lookarounds : 由于split接受正则表达式,您可以使用lookarounds

out.split("(?<=\\s)|(?=\\s)");

This will output: 这将输出:

[SELECT,  , *,  , FROM,  , EMP,  , WHERE,  , EMPID=10]

Note that the delimiter (space in your case) is included in the result. 请注意,分隔符(在您的情况下为空格)包含在结果中。

Try to split it like this: 尝试将其拆分为:

  String array[] = out.split("(?=\\s)",-1);

The code is: 代码是:

 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);
    }
  }

Output: 输出:

SELECT * FROM EMP WHERE EMPID=10

Try this one, 试试这个,

String out="SELECT * FROM EMP WHERE EMPID=10";
    out = out.replaceAll("\\s+", ",[WHITE SPACE],");

    String [] array = out.split(",");

    ArrayList<String> list = new ArrayList<String>();

    for(String str : array){
        list.add(str);
    }
    System.out.println(list);

output : 输出: 在此输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM