0

Hi I am new to Java and trying to use the split method provided by java.

The input is a String in the following format

broadcast message "Shubham Agiwal"

The desired output requirement is to get an array with the following elements

 ["broadcast","message","Shubham Agiwal"]

My code is as follows

  String str="broadcast message \"Shubham Agiwal\"";
    for(int i=0;i<str.split(" ").length;i++){
        System.out.println(str.split(" ")[i]);
    }

The output I obtained from the above code is

["broadcast","message","\"Shubham","Agiwal\""]

Can somebody let me what I need to change in my code to get the desired output as mentioned above?

shubhamagiwal92
  • 1,362
  • 4
  • 25
  • 47
  • 4
    [Split string on spaces in Java, except if between quotes](http://stackoverflow.com/questions/7804335/split-string-on-spaces-in-java-except-if-between-quotes-i-e-treat-hello-wor), [Tokenizing a String but ignoring delimiters within quotes](http://stackoverflow.com/questions/3366281/tokenizing-a-string-but-ignoring-delimiters-within-quotes), [Regex for splitting a string using space when not surrounded by single or double quotes](http://stackoverflow.com/questions/366202/regex-for-splitting-a-string-using-space-when-not-surrounded-by-single-or-double) – Tushar Oct 24 '16 at 02:58
  • 1
    The double split looks dodgy. – Scary Wombat Oct 24 '16 at 02:59
  • 1
    You code calls `split` 9 times, producing the same result each time. Although the code doesn't do what you want, next time you want to write something like this, it's both more readable and faster to save the result in an array first, before the loop. – ajb Oct 24 '16 at 03:31
  • @tushar please provide the link as an answer so that I can accept your answer – shubhamagiwal92 Oct 24 '16 at 05:31

3 Answers3

1

this is hard to split string directly.So, i will use the '\t' to replace the whitespace if the whitespace is out of "". My code is below, you can try it, and maybe others will have better solution, we can discuss it too.

package com.code.stackoverflow;

/** * Created by jiangchao on 2016/10/24. */

public class Main {

public static void main(String args[]) {
    String str="broadcast message \"Shubham Agiwal\"";
    char []chs = str.toCharArray();
    StringBuilder sb = new StringBuilder();
    /*
    * false: means that I am out of the ""
    * true: means that I am in the ""
    */
    boolean flag = false;
    for (Character c : chs) {
        if (c == '\"') {
            flag = !flag;
            continue;
        }
        if (flag == false && c == ' ') {
            sb.append("\t");
            continue;
        }
        sb.append(c);
    }
    String []strs = sb.toString().split("\t");
    for (String s : strs) {
        System.out.println(s);
    }
}

}

jiangchao
  • 11
  • 2
0

This is tedious but it works. The only problem is that if the whitespace in quotes is a tab or other white space delimiter it gets replaced with a space character.

    String str = "broadcast message \"Shubham Agiwal\" better \"Hello java World\"";
    Scanner scanner = new Scanner(str).useDelimiter("\\s");
    while(scanner.hasNext()) {
        String token = scanner.next();
        if ( token.startsWith("\"")) { //Concatenate until we see a closing quote
            token = token.substring(1);
            String nextTokenInQuotes = null;
            do {
                nextTokenInQuotes = scanner.next();
                token += " ";
                token += nextTokenInQuotes;
            }while(!nextTokenInQuotes.endsWith("\""));

            token = token.substring(0,token.length()-1); //Get rid of trailing quote
        }

        System.out.println("Token is:" + token);
    }

This produces the following output:

Token is:broadcast
Token is:message
Token is:Shubham Agiwal
Token is:better
Token is:Hello java World
cswace
  • 1
  • 1
  • I followed @Tushar link to the original solution. Very elegant solution to the problem. Thanks – cswace Oct 24 '16 at 07:12
-1
public static void main(String[] arg){
    String str = "broadcast message \"Shubham Agiwal\"";
    //First split 
    String strs[] = str.split("\\s\"");
    //Second split for the first part(Key part)
    String[] first = strs[0].split(" ");
    for(String st:first){
        System.out.println(st);
    }
    //Append " in front of the last part(Value part)
    System.out.println("\""+strs[1]);
}
zawhtut
  • 8,335
  • 5
  • 52
  • 76