Java

java怎么找出重复的字符串

小亿
128
2023-11-14 13:38:24
栏目: 编程语言

要找出重复的字符串,可以使用HashMap来记录每个字符串出现的次数。

具体步骤如下:

  1. 创建一个HashMap对象,键为字符串,值为该字符串在输入中出现的次数。
  2. 遍历输入的字符串数组或列表。
  3. 对于每个字符串,检查它是否已经在HashMap中存在。
    • 如果存在,则将该字符串的次数加1。
    • 如果不存在,则将该字符串作为键加入HashMap,并将其次数设置为1。
  4. 最后,遍历HashMap的所有键值对,找到出现次数大于1的字符串,即为重复的字符串。

以下是一个示例代码:

import java.util.HashMap;
import java.util.Map;

public class FindDuplicateStrings {
    public static void main(String[] args) {
        String[] strings = {"hello", "world", "hello", "java", "world"};

        Map<String, Integer> stringCountMap = new HashMap<>();

        for (String str : strings) {
            if (stringCountMap.containsKey(str)) {
                int count = stringCountMap.get(str);
                stringCountMap.put(str, count + 1);
            } else {
                stringCountMap.put(str, 1);
            }
        }

        for (Map.Entry<String, Integer> entry : stringCountMap.entrySet()) {
            if (entry.getValue() > 1) {
                System.out.println("重复字符串:" + entry.getKey());
            }
        }
    }
}

执行以上代码,输出结果为:

重复字符串:hello
重复字符串:world

0
看了该问题的人还看了