实现字符串倒序的总结

public class Test{
    public static void main(String[] args){

        String str = "swiss";

        //charArray()和contains()①
        char[] temp1 = str.toCharArray();
        String temp2 = "";
        for(int x = 0;x<temp1.length-1;x++){
            String temp3 = temp1[x]+"";
            if(!temp2.contains(temp3)){
                //如果不包含该字符,加入新串
                temp2 = temp2 + temp1[x];
            }
        }
        System.out.println(temp2);

        //indexOf和lastIndexOf②
        //缺点:字符的位置会有问题,结合StringBuffer倒序处理以后会解决,或者用for先倒序
        for(int x = 0;x < str.length();x++){
            String temp = str.charAt(x)+"";
            if(str.indexOf(temp)!=str.lastIndexOf(temp)){
                //如果索引不相等,把第一个字符串替换掉
                str=str.replaceFirst(temp,"");
            }
        }
        System.out.println(str);

        //replace③
        //最好的方法,最常用的方法
        while(str.length()>0){
                        //取出0号位置的字符,加入新串,然后在老串删除该字符(自己想的,但是过后居然看不懂了,补个说明)
            String temp = str.charAt(0)+ "";
            System.out.print(temp);
            str = str.replace(temp,"");
        }
        System.out.println();
        //split() 和equals()
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容