-7

I have a problem in my assigment, I want to invert a word like "Indonesia" to "aisenodnI".

public static void main (String[]args){    
    balik();    
}

public static void balik (String nama){    
    for ( i>=nama.Length-1 ; i=0 ; i-- ){    
       balik = balik + nama.Length();
       System.out.print(balik);    
    }
}
Dev-iL
  • 23,742
  • 7
  • 57
  • 99

2 Answers2

1

You can use StringBuffer or StringBuilder for this task, StringBuilder would be my choice since its more efficient. its not thread safe so multiple threads can call its methods simultaneously.

String reversedString = new StringBuilder(originalString).reverse().toString()

If you prefer not to use API support you can do something like this

static String reverse(String stringIn) {
    char[] cArr = stringIn.toCharArray();
    for (int i = 0; i < cArr.length/2; ++i){
        char c = cArr[i];
        cArr[i] = cArr[cArr.length-1-i];
        cArr[cArr.length-1-i] = c;
    }
    return new String(cArr);
}
Ulug Toprak
  • 1,172
  • 1
  • 10
  • 21
  • While this code may answer the question, providing additional [context](https://meta.stackexchange.com/q/114762) regarding _how_ and/or _why_ it solves the problem would improve the answer's long-term value. Remember that you are answering the question for readers in the future, not just the person asking now! Please [edit](http://stackoverflow.com/posts/43319617/edit) your answer to add an explanation, and give an indication of what limitations and assumptions that apply. It also doesn't hurt to mention why this answer is more appropriate than others. – Dev-iL Apr 10 '17 at 10:38
  • @Dev-iL you are totally right – Ulug Toprak Apr 10 '17 at 10:58
0

If only reversing of the string is needed then you can go with the below method.

String name= "India";
String reverseString = new StringBuffer(name).reverse().toString();
System.Out.Println("reversed sstring is "+reverseString );
Div
  • 99
  • 1
  • 1
  • 7