Java实现字符串反转

Posted on 2016-03-29 15:06  jackley  阅读(129)  评论(0)    收藏  举报


本案例需要完成的任务定义如下:定义和实现一个接口,并使用其完成字符串的反转。


定义接口:

public interface InterReverse{

         public String ireverse(String str);
}

 

实现接口:

基本思想是用charAt()方法将字符串打散为字符,用char型数组c[]存储反转后后的字符,最后用String的静态方法valueOf()将反转后的字符数组转换为字符串。

public class ReverseTest implement InterReverse{

         public String ireverse(String str){

                   char[] c = char[str.length()];

                   int i;

                   for(i=str.length()-1;i>=0;i--)

                            c[str.length()-1-i] = str.charAt(i);

return String.valueOf(c);

}

 

public static void main(String[] args){

         ReverseTest test = new ReverseTest();

         System.out.println(test.ireverse("Hello world!"));

}

}