【java】将字符串反转

解法一:

设计这个方法:

首先考虑:

  • 是否需要参数 String
  • 是否有返回值 String

public class Demo {

    public String reverse(String s){       //反转字符串的方法
        char[] value = s.toCharArray();
        char temp;
        for(int i = 0; i < value.length/2; i++){
            temp = value[i];
            value[i] = value[value.length-1-i];
            value[value.length-1-i] = temp;
        }
        return new String(value);
    }

    public static void main(String[] args){
        Demo demo = new Demo();
        String str = "zgh666";
        System.out.println(demo.reverse(str));//666hgz
    }
}


解法二:

StringBufferStringBuilder中都有一个方法reverse();


public class Demo {

    public String reverse(String s){

        return new String(new StringBuilder(s).reverse());
        //return new String(new StringBuffer(s).reverse());
    }

    public static void main(String[] args){
        Demo demo = new Demo();
        String str = "zgh666";
        System.out.println(demo.reverse(str));//666hgz
    }
}

你可能感兴趣的:(Java)