JohnBigs
JohnBigs

Reputation: 2811

Getting error trying to reverse a string in Java

I'm trying to do a simple reverse task like: change the string "how are you" to "you are how".

this is my code:

public class Program {
    public static String revSentence (String str) {
        String [] givenString = str.split(" ");
        String [] retString = new String[givenString.length];

        int last = givenString.length - 1;

        for (int i = 0; i < givenString.length; i++) {
            retString [i] = givenString[last--]; 
        }

        return retString.toString();
    }

    public static void main(String[] args) {
        String m = "how are you";
        System.out.println(revSentence(m));
    }
}

I'm getting a weird output:

[Ljava.lang.String;@e76cbf7

Upvotes: 1

Views: 125

Answers (7)

Mohsin AR
Mohsin AR

Reputation: 3108

the for loop start from greater length to lower and builder.append(givenString[i] + " "); this will concatenate String and return whole sentence you are how you could use both mySentence += givenString[i] + " "; or builder.append(givenString[i] + " "); but the best way is to use StringBuilder class (see docs)

public class Program {
public static String revSentence(String str) {
    String[] givenString = str.split(" ");
    String[] retString = new String[givenString.length];

    int last = givenString.length - 1;
    //String mySentence = "";

    StringBuilder builder = new StringBuilder();

    for (int i = givenString.length - 1; i >= 0; i--) {
        // retString [i] = givenString[i];
        // mySentence += givenString[i] + " ";
        builder.append(givenString[i] + " ");
    }

    return builder.toString(); // retuning String
            //return mySentence;
}

public static void main(String[] args) {
    String m = "how are you";
    System.out.println(revSentence(m));
}

}

Upvotes: 0

Alvin Bunk
Alvin Bunk

Reputation: 7764

Here is a solution:

public class Program {
    public static String revSentence (String str) {
        String retString = "";
        String [] givenString = str.split(" ");

        for (int i=givenString.length-1; i>=0; i--) {
            retString += givenString[i] + " "; 
        }
        return retString;
    }


    public static void main(String[] args) {
        String m = "how are you";
        System.out.print(revSentence(m));
    }

}

Modified it to make the "revSentence" function return a String, plus improved the code a bit. Enjoy!

Upvotes: 2

Johannes H.
Johannes H.

Reputation: 6167

The output isn't "weird" at all - it's the Object's internal string representation, created by Object.toString(). String[] doesnt override that. If you want to output all entires, loop through them and concatenate them, Best using a StringBuilder to avoid creating unnecessary String instances.

public static String arrayToString (String[] array) {
    StringBuilder result = new StringBuilder();
    for (String value : array) {
        result.append(value);
    }
    return StringBuilder.toString();
}

If you don'T need that method on it'S own and want to include it in the overall process of reversing the sentence, this is how it may look. It iterates only once, iterating backwards (= counting down) to reverse the sentence.

public static String revSentence (String str) {
    String []     givenString = str.split(" ");
    StringBuilder result      = new StringBuilder();

    // no need for 'last', we can use i to count down as well...
    for (int i = givenString.length - 1 ; i >= 0; i--) { 
        result.append(givenString[i]);
    }
    return result.toString();
}

[Edit]: because of the OPs comment to one of the other answers, about not having learned how to use StringBUilder yet, here is a arrayToStirng method without using one. Note however that this should not be done normally, as it creates useless instances of String whiche are not cleaned up by the GC because of the immutable nature of String(all instances are kept for reuse).

public static String arrayToString (String[] array) {
    String result = "";
    for (String value : array) {
        result += value;
    }
    return result;
}

Or, without a dedicate arrayToString method:

public static String revSentence (String str) {
    String []     givenString = str.split(" ");
    String        result      = "";

    for (int i = givenString.length-1 ; i >= 0 ; i--) { 
        result += givenString[i];
    }
    return result;
}

Upvotes: 4

AlexWien
AlexWien

Reputation: 28727

Faster, and shorter: To reverse a word, use:

public String reverseWord(String s) {
    StringBuilder y = new StringBuilder(s);
    return y.reverse();
}

Now split and use this method and use Stringbuidler.append to concatenate the all. And dont forget the space inbetween.

Upvotes: -1

LINEMAN78
LINEMAN78

Reputation: 2562

Calling toString on an array gives you the memory ref which isn't very useful. Try this:

public static String revSentence (String str) {
    String[] givenString = str.split(" ");

    StringBuilder sb = new StringBuilder();
    for (int i = givenString.length - 1; i >= 0; i--) {
        sb.append(givenString[i]);
        if (i != 0)
          sb.append(" ");
    }
    return sb.toString();
}

Upvotes: 0

Wajahat
Wajahat

Reputation: 1633

Use this code for reversed string

StringBuilder builder = new StringBuilder();
for(String s : retString) {
    builder.append(s);
}
return builder.toString();

Upvotes: 1

Juvanis
Juvanis

Reputation: 25950

Calling toString() on an array object (in your case retString) doesn't print all array entries, instead it prints object address.

You should print array entries by iterating over them.

Upvotes: 1

Related Questions