Reverse a string in Java

前端 未结 30 2623
礼貌的吻别
礼貌的吻别 2020-11-21 13:12

I have \"Hello World\" kept in a String variable named hi.

I need to print it, but reversed.

How can I do this? I understand there

30条回答
  •  心在旅途
    2020-11-21 14:03

    I am doing this by using the following two ways:

    Reverse string by CHARACTERS:

    public static void main(String[] args) {
        // Using traditional approach
        String result="";
        for(int i=string.length()-1; i>=0; i--) {
            result = result + string.charAt(i);
        }
        System.out.println(result);
    
        // Using StringBuffer class
        StringBuffer buffer = new StringBuffer(string);
        System.out.println(buffer.reverse());    
    }
    

    Reverse string by WORDS:

    public static void reverseStringByWords(String string) {
        StringBuilder stringBuilder = new StringBuilder();
        String[] words = string.split(" ");
    
        for (int j = words.length-1; j >= 0; j--) {
            stringBuilder.append(words[j]).append(' ');
        }
        System.out.println("Reverse words: " + stringBuilder);
    }
    

提交回复
热议问题