문자열을 역순으로 출력합니다. 예를 들어 abcd 를 dcba 로 출력합니다.

// ex.1)
public class Ex01{
    public static void main(String[] args) {
        String str = "Reverse this Strings";        
        String new_str = "";
 
        for (int i = str.length()-1; i > -1; i--) {
            new_str += str.charAt(i);
        }
        System.out.println(new_str);
    }   
}


아래는 결과 화면입니다.

 

// ex.2)
public class Ex01{
    public static void main(String[] args) {
        String str = "Reverse this Strings";        
        String new_str = "";
 
        String[] str1 = str.split("");
        for (int i = str1.length-1; i > -1; i--) {
            new_str += str1[i];
        }
        System.out.println(new_str);
    }   
}


다음은 StringBuffer 를 이용해 문자열을 역순으로 정렬합니다. 

// ex.3)
public class Ex01{
    public static void main(String[] args) {
        String str = "Reverse this Strings";
         
        StringBuffer reverse = new StringBuffer(str);
        System.out.println(reverse.reverse());
    }   
}


// ex.4)
public class Ex01{
    public static void main(String[] args) {
        String str = "Reverse this Strings";
         
        StringBuffer reverse = new StringBuffer();
        reverse.append(str);
        System.out.println(reverse.reverse());
    }   
}


0 댓글