我需要在使用" "
分隔符拆分字符串后添加空格。我需要这样做的原因是因为在下一个String的开头没有添加空格,如下例所示:
"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 :(得分: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
是一个单词,并且无法单独反转Alice
和think
。
如果这是家庭作业,我认为你的代码目前正在做它应该做的事情。如果有疑问,请询问您的导师。
答案 1 :(得分:0)
您的原始字符串也已加入Alice" + "think
,您需要将其更新为Alice " +"think
或Alice" + " think