Reverse a string in Java

前端 未结 30 3083
礼貌的吻别
礼貌的吻别 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 13:47

    You can use this:

    new StringBuilder(hi).reverse().toString()
    

    Or, for versions earlier than JDK 1.5, use java.util.StringBuffer instead of StringBuilder — they have the same API. Thanks commentators for pointing out that StringBuilder is preferred nowadays when there is no concurrency concern.

提交回复
热议问题