zoukankan      html  css  js  c++  java
  • 检测传入字符串是否存在重复字符,返回boolean

    检测传入字符串是否存在重复字符,返回boolean,比如"abc"返回true;"aac"返回false

    这里提供两种思路:

    第一种:

    import java.util.HashSet;
    import java.util.Set;
    
    
    public class Test {
    
        public static boolean checkDifferent2(String iniString) {
            
            //将参数的每一个字符都写入数组
            String[] a = iniString.split("");
            //这里使用Set类下的HashSet对象,该对象是不允许重复的
            Set a1 = new HashSet<String>();
            //将参数数组内的值挨个赋到HashSet中
            for(int i=0; i<a.length; i++) {
                a1.add(a[i]);
            }
            //将HashSet重新转化为数组
            Object[] b = a1.toArray();
            //通过对比两个数组长度来查看是否有重复字符存在
            return a.length == b.length;       
        }
        
    }

    第二种:

    /*
         * 使用String的charAt()方法,利用循环嵌套拿出字符串中每一个字符进行对比
         */
        public static boolean checkDifferent(String iniString) {
            boolean result = false;
            if (iniString.length() > 1) {
                
                for(int i=0; i<iniString.length(); i++) {
                    for(int l=0; l<iniString.length(); l++) {
                        if (i==l){
                            continue;
                            } else {
                            if (iniString.charAt(i)!=iniString.charAt(l)) {
                                result = true;
                            } else {
                                return result = false;
                            }
                        }
                    }
                }
                
            } else {
                result = true;
            }
            return result;
        }
        
    
    }
  • 相关阅读:
    ORM框架
    优酷项目1
    新年第一天
    前端第十天
    前端第九天
    前端第八天
    前端第七天
    前端第六天
    前端第五天
    月亮与六便士
  • 原文地址:https://www.cnblogs.com/JianXu/p/5708035.html
Copyright © 2011-2022 走看看