如何对比单个字符串元素与字符串数组元素?及现有统计代码疑问
嘿,我来帮你搞定这两个问题!
问题1:单个字符串元素与字符串数组的比较方法
这里有几种实用的方式,根据你的场景选就行:
- 循环遍历逐一对比:最基础直接的方法,记得用
equals()(别用==,它比的是对象引用,不是字符串内容):
String target = "apple"; String[] fruitArray = {"banana", "apple", "orange"}; boolean isExists = false; for (String fruit : fruitArray) { if (target.equals(fruit)) { isExists = true; break; // 找到就提前退出循环 } } // 此时isExists为true,说明数组里有目标字符串
- 转集合用contains():借助集合的内置方法,代码更简洁:
String target = "apple"; String[] fruitArray = {"banana", "apple", "orange"}; // 转成Set(适合频繁查询的场景) Set<String> fruitSet = new HashSet<>(Arrays.asList(fruitArray)); boolean existsInSet = fruitSet.contains(target); // 或者转成List(保留顺序) List<String> fruitList = Arrays.asList(fruitArray); boolean existsInList = fruitList.contains(target);
- Java 8+ 流式操作:用Stream的
anyMatch()一行搞定,可读性拉满:
String target = "apple"; String[] fruitArray = {"banana", "apple", "orange"}; boolean exists = Arrays.stream(fruitArray).anyMatch(target::equals);
问题2:你的
StringCheck函数分析与优化 先夸一句:你的核心逻辑是对的——通过Set求交集来统计公共元素数量,思路很清晰!不过可以做些优化,同时提前规避调用时可能踩的坑:
简化现有代码
你手动循环往Set里加元素的部分可以用Arrays.asList()直接初始化,同时加上null判断避免崩溃:
public void StringCheck(String one, String two) { // 处理null输入,避免NullPointerException String[] subStrings1 = one != null ? one.split(", ") : new String[0]; String[] subStrings2 = two != null ? two.split(", ") : new String[0]; // 直接用Arrays.asList初始化Set,省去循环 Set<String> set1 = new HashSet<>(Arrays.asList(subStrings1)); Set<String> set2 = new HashSet<>(Arrays.asList(subStrings2)); set1.retainAll(set2); // 求交集 textView3.setText(String.valueOf(set1.size())); // 用String.valueOf比拼接空字符串更规范 }
调用时要注意的坑
- 空值/空字符串处理:如果传入的
one或two是null,原代码会直接抛异常,上面的优化已经解决了这个问题;如果是空字符串,分割后会得到一个包含空字符串的数组,如果你不想统计空字符串,可以在转Set前过滤掉:
// 过滤空字符串 String[] subStrings1 = one != null ? Arrays.stream(one.split(", ")) .filter(s -> !s.isEmpty()) .toArray(String[]::new) : new String[0];
- 分隔符不一致:如果输入字符串里的分隔符不是
,(比如逗号后没空格、用分号),分割结果会出错,要么提前约定好输入格式,要么让分隔符更灵活(比如用split("\\s*,\\s*")匹配逗号前后的任意空格)。 - 重复元素统计:原代码用HashSet会自动去重,如果你需要统计重复元素的实际出现次数(比如str1有2个"apple",str2有1个,公共数量算2),那得用Map统计次数再计算:
public void StringCheckWithDuplicates(String one, String two) { if (one == null || two == null) { textView3.setText("0"); return; } String[] subStrings1 = one.split(", "); String[] subStrings2 = two.split(", "); // 统计每个元素的出现次数 Map<String, Integer> countMap1 = new HashMap<>(); for (String s : subStrings1) { countMap1.put(s, countMap1.getOrDefault(s, 0) + 1); } Map<String, Integer> countMap2 = new HashMap<>(); for (String s : subStrings2) { countMap2.put(s, countMap2.getOrDefault(s, 0) + 1); } // 计算公共元素的总次数 int totalCommon = 0; for (String key : countMap1.keySet()) { if (countMap2.containsKey(key)) { totalCommon += Math.min(countMap1.get(key), countMap2.get(key)); } } textView3.setText(String.valueOf(totalCommon)); }
调用示例
比如你可以这样测试:
String str1 = "apple, banana, orange, apple"; String str2 = "banana, orange, grape"; // 调用原方法会返回2(去重后的公共元素数) StringCheck(str1, str2); // 调用带重复统计的方法会返回2(banana1次 + orange1次) StringCheckWithDuplicates(str1, str2);
内容的提问来源于stack exchange,提问作者Serkan Tarakcı
相关产品推荐
相关产品推荐

