0

I'm trying to parse input on spaces and put these tokens into an array. But taked quoted string as a one word. For example, assume input is:

dsas r2r "this is a sentence" asd

and array elements should be:

array[0]="dsas"
array[1]="r2r"
array[2]="this is a sentence"
array[3]="asd"

To solve the problem I used split method but it didn't help to me

   String input1=input.nextLine();
   input1=input1.trim();
   String delims="[ \"]+";
   String[] array=input1.split(delims);

How can I fix this problem? I have to put tokens into an array and i have to don't use arraylist.

gdiazc
  • 2,108
  • 4
  • 19
  • 30
Abraam
  • 13
  • 1
  • 3

1 Answers1

0

You can try this. Please note, I quickly written this code, may contains bug. I have used ArrayList to store the phrases(because of time crunch!) you can use an array(String[]) easily.

    String input1="dsas r2r   \"this is a sentence\"   asd";
       input1=input1.trim();
       char[] charArray = input1.toCharArray();
       String word = "";
       List<String> strList = new ArrayList<>();
       boolean skipAll = false;
       for(char tempChar : charArray) {
           if( tempChar == '"') {
               skipAll = !skipAll;
           } 
           if( tempChar != ' ' && !skipAll) {
               word += tempChar;  
           } else if( tempChar == ' ' && word.length() > 0 && !skipAll) {
               strList.add(word);
               word = "";
           } else if(skipAll) {
               word += tempChar;
           }
       }
       if(word.length() > 0)
           strList.add(word);

       System.out.println(strList);
A Paul
  • 8,113
  • 3
  • 31
  • 61