James B
James B

Reputation: 231

Java - add a space after splitting a String

I need to add a space after splitting a String with a " " delimiter. The reason I need to do this is because a space has not been added at the start of the next String as shown in this example:

"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"

My code below only splits the string (and reverses it), but the concatenations produce the following result (Notice where "Alicethink" is joined together):

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

Code:

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);

How can I fix it?

EDIT: Here is the whole String:

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.";

Upvotes: 0

Views: 74

Answers (2)

The Guy with The Hat
The Guy with The Hat

Reputation: 11132

If the original string is

"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"

that is seen by your code as

"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"

After that concatenation (which happens in compilation, I believe), Alicethink is a single word, and there is no way to reverse Alice and think individually.

If this is a homework assignment, I think your code is currently doing what it's supposed to. If there is doubt, ask your instructor.

Upvotes: 1

Liping Huang
Liping Huang

Reputation: 4476

Your original string is also joined Alice" + "think, you need update it to Alice " +"think or Alice" + " think

Upvotes: 0

Related Questions