2016-10-09 63 views
0

我需要在用" "分隔符分割字符串之後添加空格。我需要做的原因是因爲空間沒有被下一個字符串的開頭添加本例所示:Java - 在分割字符串後添加一個空格

"There was nothing so VERY remarkable in that; nor did Alice" + 
"think it so VERY much out of the way to hear the Rabbit say to" 

我下面只代碼分割字符串(和反轉),但在級聯產生以下結果(注意這裏的 「Alicethink」 是連在一起):

erehT saw gnihton os YREV elbakramer ni ;taht ron did knihtecilA 
ti os YREV hcum tuo fo eht yaw ot raeh eht tibbaR yas 

代碼:

String[] text = PROBLEM5PARA.split(" "); 
String reverseString = ""; 

for (int i = 0; i < text.length; i++) { 

    String word = text[i]; 
    String reverseWord = ""; 

    for (int j = word.length()-1; j >= 0; j--) { 
     reverseWord += word.charAt(j); 
    } 

    reverseString += reverseWord + " "; 
} 

System.out.println(reverseString); 

我怎樣才能解決這個問題?

編輯: 這裏是整個字符串:

private static final String PROBLEM5PARA = 
     " There was nothing so VERY remarkable in that; nor did Alice" + 
       "think it so VERY much out of the way to hear the Rabbit say to" + 
       "itself, `Oh dear! Oh dear! I shall be late!' (when she thought" + 
       "it over afterwards, it occurred to her that she ought to have" + 
       "wondered at this, but at the time it all seemed quite natural);" + 
       "but when the Rabbit actually TOOK A WATCH OUT OF ITS WAISTCOAT-" + 
       "POCKET, and looked at it, and then hurried on, Alice started to" + 
       "her feet, for it flashed across her mind that she had never" + 
       "before seen a rabbit with either a waistcoat-pocket, or a watch to" + 
       "take out of it, and burning with curiosity, she ran across the" + 
       "field after it, and fortunately was just in time to see it pop" + 
       "down a large rabbit-hole under the hedge."; 
+0

如何判斷拆分後哪個單詞應該分離? – passion

回答

0

你原來的字符串,也加入Alice" + "think,你需要將其更新到Alice " +"thinkAlice" + " think

+0

我想知道是否有方法來設置字符串後做到這一點。 –

+0

@JamesB不,沒有。 –

1

如果原始字符串

"There was nothing so VERY remarkable in that; nor did Alice" + "think it so VERY much out of the way to hear the Rabbit say to" 

您的代碼看起來像是

"There was nothing so VERY remarkable in that; nor did Alicethink it so VERY much out of the way to hear the Rabbit say to" 

該級聯之後(發生在編寫,我相信),Alicethink是一個字,也沒有辦法扭轉Alicethink獨立。

如果這是一項家庭作業,我認爲你的代碼正在做它應該做的。如果有疑問,請詢問你的導師。

+0

謝謝,這是一項家庭作業,任務完成我只是出於興趣而問。 –