计算不同的字符而不转换为小写

counting different chars without converting to lower case

方法:

public static int noOfLetters (String str)

我得到一个字符串,需要 return 字符串中唯一字母的数量,大写字母和小写字母被认为是相等的,但你不能将它们转换为小写字母,反之亦然。我尝试了很多东西。这是我能编写的最好的代码: 例如:"cd$aD" 会 return 3

public static int noOfLetters(String str) {
    char[] alphabet = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
    int count = 0;
    int j = 0;
    for(int i=0;i<str.length();i++) {
        if(str.charAt(i) != alphabet[j])
            j++;
        count++;
    }
    return count;

我建议你枚举字符并将它们放在不区分大小写的映射中。

在循环结束时,您应该获取键集合大小以获得唯一字母的数量。

这里https://www.baeldung.com/java-map-with-case-insensitive-keys是关于如何使用不区分大小写的地图的教程。 .

你可以用

str.chars().filter(ch -> (ch >= 65 && ch <= 90) || (ch >= 97 && ch <= 122)).map(ch -> ch >= 97? ch-32 : ch).distinct().count();

您首先过滤掉所有不同于字母的字符,然后将所有字符都转换为大写,但如果这是不允许的,则您没有使用 toLowercase 或 toUppercase 方法

您可以使用 Set<Character> 来添加您看到的每个字母字符:

要了解技巧,您可以访问:ASCII Table

public static int noOfLetters(String str) {
    List<Character> alphabet = Arrays.asList('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z');
    Set<Character> uniqueAlphabetSeen = new HashSet<>();

    for (int i = 0; i < str.length(); i++) {
        char c = str.charAt(i);

        if (alphabet.contains(c)){
            uniqueAlphabetSeen.add(c);
        }
        else if(c >= 'A' && c <= 'Z'){
            uniqueAlphabetSeen.add((char) (c -'A' + 'a'));
        }
    }

    return uniqueAlphabetSeen.size();
}

输入:

System.out.println(noOfLetters("cd$aD"));

输出:

3

我认为你应该能够通过在循环中为位于 'A''Z' 之间的所有字符添加一个条件来做到这一点,你可以通过从 [=] 中减去它来将其转换为小写13=]:

public static int noOfLetters(String str) {
    Set<Character> distinctChars = new HashSet<>();
    for (int i = 0; i < str.length(); i++) {
        boolean isUpperCaseChar = str.charAt(i) >= 'A' && str.charAt(i) <= 'Z';
        boolean isLowerCaseChar = str.charAt(i) >= 'a' && str.charAt(i) <= 'z';
        if (isUpperCaseChar || isLowerCaseChar) {
            char convertedLowerCaseChar = str.charAt(i);
            if (isUpperCaseChar) {
                convertedLowerCaseChar = (char) (str.charAt(i) - 'A' + 'a');
            }
            distinctChars.add(convertedLowerCaseChar);
        }
    }

    return distinctChars.size();
}

我用这段代码测试了它:

System.out.println(noOfLetters("rohankumar"));
System.out.println(noOfLetters("rohankumarROHAN"));
System.out.println(noOfLetters("rohankumarROHAN-$"));
System.out.println(noOfLetters("cd$aD"));

它打印以下内容:

8
8
8
3