2014-03-31 49 views
0

我試圖解析空格上的輸入並將這些標記放入數組中。但是被引用的字符串是一個單詞。例如,假定輸入是:空格上的標記字符串,除非在引號之間

dsas r2r "this is a sentence" asd 

和數組元素應該是:

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

爲了解決我用分裂法的問題,但它並沒有幫助我

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

我該如何解決這個問題?我必須將標記放入數組中,而且我不得不使用數組列表。

+0

輸入字符串實際上看起來像什麼?它實際上是否包含雙引號? –

+0

嘗試'String delims =「[] +(?=([^」] *「[^」] *「)* [^」] * $)「' – Omoro

回答

0

你可以試試這個。請注意,我很快寫了這個代碼,可能包含bug。我已經使用ArrayList來存儲短語(因爲時間緊迫!),您可以輕鬆地使用數組(String [])。

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); 
相關問題