Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning a string entered as reverse text in Java

Tags:

java

string

I'm trying to make a method that returns a string of words in opposite order.

IE/ "The rain in Spain falls mostly on the" would return: "the on mostly falls Spain in rain The"

For this I am not supposed to use any built in Java classes just basic Java.

So far I have:

    lastSpace = stringIn.length(); 

    for (int i = stringIn.length() - 1; i >= 0; i--){
        chIn = stringIn.charAt(i);
        if (chIn == ' '){
            word = stringIn.substring(i + 1, lastSpace);
            stringOut.concat(word);
            lastS = i;
        }
    }
    word = stringIn.substring(0,lastSpace);
    stringOut.concat(word);

    return stringOut;

My problem is when stringOut is returned to its caller it always is a blank string.

Am I doing something wrong? Maybe my use of string.concat()?

like image 758
SaFruk Avatar asked Feb 01 '09 21:02

SaFruk


1 Answers

In Java, Strings are immutable, i.e. they can't be changed. concat() returns a new string with the concatenation. So you want something like this:

stringOut = stringOut.concat(word);

or

stringOut += word

as Ray notes, there are more succinct ways to do this though.

like image 118
Dave Ray Avatar answered Sep 28 '22 14:09

Dave Ray