【问题标题】:Check if there is a duplicate letter within a string regardless of lowercase or uppercase检查字符串中是否有重复的字母,无论是小写还是大写
【发布时间】:2021-08-12 07:17:24
【问题描述】:
public static boolean check(String input) {
    Set<Character> tmp = new HashSet<Character>();
    for(char ch : input.toCharArray()) {
        if (Character.isLetter(ch) && !tmp.add(ch)) {
            return true;
        }
    }
    return false;
}

我对编程很陌生,我找到了一种在字符串中查找重复字母的方法,但是如果重复的字母是大写字母或非大写字母,例如“Aa”,我将如何返回 true。

【问题讨论】:

    标签: java arrays for-loop if-statement


    【解决方案1】:

    在 for 循环之前将 input 更改为小写。

    public static boolean check(String input) {
        Set<Character> tmp = new HashSet<Character>();
        // This will make all capital letters lowercase but will not change the original string
        String testInput = input.toLowerCase();
        for(char ch : testInput.toCharArray()) {
            if (Character.isLetter(ch) && !tmp.add(ch)) {
                return true;
            }
        }
        return false;
    }
    

    【讨论】:

    • 对不起,我不明白你的意思。
    • @AranRassull - 我已经更新了答案以包含代码。如果您需要解释为什么这样做有效,请告诉我。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-02-03
    • 2014-02-12
    • 1970-01-01
    • 1970-01-01
    • 2018-08-22
    • 2017-01-16
    • 2011-02-18
    相关资源
    最近更新 更多