Sunday, November 23, 2014

Lesson 43: String reverse in Java

actually there are 2 ways i can think of, the first one is using API from Java and the second one you can construct StringBuilder and append characters from end to first of string.

     str1 = "HELLO WORLD";
     //cara 1
     System.out.println(new StringBuilder(str1).reverse().toString());
   
     //cara 2
     StringBuilder sb = new StringBuilder(str1.length());    
     for(int j=str1.length()-1; j>=0; j-- ){
     sb.append(str1.charAt(j));
     }
     System.out.println(sb.toString());

No comments:

Post a Comment