Carol.Kar
Carol.Kar

Reputation: 5345

Word reversion of a string

I want to reverse words in a String. I tried to implement it like that:

public String reverseWords(String str) {
    String reverse = "";
    String[] arr = str.split(" ");
    for (int i = arr.length; i < 0; i++) {
        reverse+=arr[i];
    }       
    return reverse;
}

However, this does not give me anything back? Any recommendations what I am doing wrong?

Upvotes: 3

Views: 213

Answers (6)

Ker p pag
Ker p pag

Reputation: 1588

if you want to use loop.

version 1:

public String reverseWords(String str) {
    String reverse = "";
    for (int i = str.length()-1; i >= 0; i--) {
        reverse+=str.charAt(i);
    }       
    return reverse;
}

version 2:

 public String reverseWords(String str) {
StringBuilder sb = new StringBuilder(str.length()+1);
        for (int i = str.length()-1; i >= 0; i--) {
            sb.append(str.charAt(i));
        }       
        return sb.toString();
    }

Upvotes: 2

Basil
Basil

Reputation: 11

I giving another option for reversing the string ie with using charArray in java. 1.copy all the string to char array using function 2. Simply print the character in reverse order.

Upvotes: 0

Arun Kumar Mudraboyina
Arun Kumar Mudraboyina

Reputation: 779

if the string having huge length, moreover if you are in multithreaded environment, it is recommended to go for StringBuffer instead of StringBuilder.

public  String reverseWords(String str) {
          return new StringBuffer(str).reverse().toString();
       }

Upvotes: 1

MichaelCMS
MichaelCMS

Reputation: 4763

try i=0 to arr.length or i-- and i>=0.

Or more elaborate :

You want

for (int i=arr.length-1 ; i>=0 ;i--)

Upvotes: 3

user3145373 ツ
user3145373 ツ

Reputation: 8146

You have to make loop iterate backward. using -- and you don't need to go from 0 to length but from length to 1. It's main logic of manual reverse function.

try this :

public static String reverseWords(String str) {
    StringBuilder sb = new StringBuilder(str.length() + 1);
    String[] words = str.split(" ");
    for (int i = words.length - 1; i >= 0; i--) {
        sb.append(words[i]).append(' ');
    }
    sb.setLength(sb.length() - 1);  // Strip trailing space
    return sb.toString();
}

Upvotes: 3

FazoM
FazoM

Reputation: 4956

You have: for (int i = arr.length; i < 0; i++) {

I will always be bigger or equal to 0 if it is length.
Try this: for (int i = arr.length; i > 0; i--) {

Upvotes: 2

Related Questions