Java 如何计算字符串中的大写和小写字母?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25224954/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 23:55:02  来源:igfitidea点击:

How to count uppercase and lowercase letters in a string?

javastringcharacter-class

提问by yyzzer1234

yo, so im trying to make a program that can take string input from the user for instance: "ONCE UPON a time" and then report back how many upper and lowercase letters the string contains:

哟,所以我试图制作一个可以从用户那里获取字符串输入的程序,例如:“一次”,然后报告字符串包含多少个大写和小写字母:

output example: the string has 8 uppercase letters the string has 5 lowercase letters, and im supposed to use string class not arrays, any tips on how to get started on this one? thanks in advance, here is what I have done so far :D!

输出示例:字符串有 8 个大写字母字符串有 5 个小写字母,我应该使用字符串类而不是数组,关于如何开始使用这个的任何提示?提前致谢,这是我到目前为止所做的:D!

import java.util.Scanner;
public class q36{
    public static void main(String args[]){

        Scanner keyboard = new Scanner(System.in);
        System.out.println("Give a string ");
        String input=keyboard.nextLine();

        int lengde = input.length();
        System.out.println("String: " + input + "\t " + "lengde:"+ lengde);

        for(int i=0; i<lengde;i++) {
            if(Character.isUpperCase(CharAt(i))){

            }
        }
    }
}

采纳答案by TNT

Simply create counters that increment when a lowercase or uppercase letter is found, like so:

只需创建在找到小写或大写字母时递增的计数器,如下所示:

for (int k = 0; k < input.length(); k++) {
    /**
     * The methods isUpperCase(char ch) and isLowerCase(char ch) of the Character
     * class are static so we use the Class.method() format; the charAt(int index)
     * method of the String class is an instance method, so the instance, which,
     * in this case, is the variable `input`, needs to be used to call the method.
     **/
    // Check for uppercase letters.
    if (Character.isUpperCase(input.charAt(k))) upperCase++;

    // Check for lowercase letters.
    if (Character.isLowerCase(input.charAt(k))) lowerCase++;
}

System.out.printf("There are %d uppercase letters and %d lowercase letters.",upperCase,lowerCase);

回答by eckes

You simply loop over the content and use the Character features to test it. I use real codepoints, so it supports supplementary characters of Unicode.

您只需遍历内容并使用 Character 功能对其进行测试。我使用真正的代码点,所以它支持 Unicode 的补充字符。

When dealing with code points, the index cannot simply be incremented by one, since some code points actually read two characters (aka code units). This is why I use the while and Character.charCount(int cp).

在处理代码点时,索引不能简单地增加 1,因为某些代码点实际上读取了两个字符(又名代码单元)。这就是为什么我使用 while 和Character.charCount(int cp).

/** Method counts and prints number of lower/uppercase codepoints. */
static void countCharacterClasses(String input) {
    int upper = 0;
    int lower = 0;
    int other = 0;

    // index counts from 0 till end of string length
    int index = 0;
    while(index < input.length()) {
        // we get the unicode code point at index
        // this is the character at index-th position (but fits only in an int)
        int cp = input.codePointAt(index);
        // we increment index by 1 or 2, depending if cp fits in single char
        index += Character.charCount(cp);

        // the type of the codepoint is the character class
        int type = Character.getType(cp);
        // we care only about the character class for lower & uppercase letters
        switch(type) {
            case Character.UPPERCASE_LETTER:
                upper++;
                break;
            case Character.LOWERCASE_LETTER:
                lower++;
                break;
            default:
                other++;
        }
    }

    System.out.printf("Input has %d upper, %d lower and %d other codepoints%n",
                      upper, lower, other);
}

For this sample the result will be:

对于此示例,结果将是:

// test with plain letters, numbers and international chars:
countCharacterClasses("AABB??o?abc0\uD801\uDC00");
      // U+10400 "DESERET CAPITAL LETTER LONG I" is 2 char UTF16: D801 DC00

Input has 6 upper, 6 lower and 1 other codepoints

It count the german sharp-s as lowercase (there is no uppercase variant) and the special supplement codepoint (which is two codeunits/char long) as uppercase. The number will be counted as "other".

它将德语sharp-s 视为小写(没有大写变体),将特殊补充代码点(两个代码单元/字符长)视为大写。该数字将被视为“其他”。

Using Character.getType(int cp)instead of Character.isUpperCase()has the advantage that it only needs to look at the code point once for multiple (all) character classes. This can also be used to count all different classes (letters, whitespace, control and all the fancy other unicode classes (TITLECASE_LETTER etc).

使用Character.getType(int cp)代替Character.isUpperCase()的优点是它只需要查看多个(所有)字符类的代码点一次。这也可以用于计算所有不同的类(字母、空格、控件和所有其他花哨的 unicode 类(TITLECASE_LETTER 等)。

For a good background read on why you need to care about codepoints und units, check out: http://www.joelonsoftware.com/articles/Unicode.html

有关为什么需要关心代码点和单位的良好背景阅读,请查看:http: //www.joelonsoftware.com/articles/Unicode.html

回答by Aditya

You can try the following code :

您可以尝试以下代码:

public class ASCII_Demo
{
    public static void main(String[] args)
    {
        String str = "ONCE UPON a time";
        char ch;
        int uppercase=0,lowercase=0;
        for(int i=0;i<str.length();i++)
        {
            ch = str.charAt(i);
            int asciivalue = (int)ch;
            if(asciivalue >=65 && asciivalue <=90){
                uppercase++;
            }
            else if(asciivalue >=97 && asciivalue <=122){
                lowercase++;
            }
        }
        System.out.println("No of lowercase letter : " + lowercase);
        System.out.println("No of uppercase letter : " + uppercase);
    }
}

回答by CMR

Use regular expressions:

使用正则表达式:

public Counts count(String str) {
    Counts counts = new Counts();
    counts.setUpperCases(str.split("(?=[A-Z])").length - 1));
    counts.setLowerCases(str.split("(?=[a-z])").length - 1));
    return counts;
}

回答by Rodolfo Martins

The solution in Java8:

Java8中的解决方案:

private static long countUpperCase(String s) {
    return s.codePoints().filter(c-> c>='A' && c<='Z').count();
}

private static long countLowerCase(String s) {
    return s.codePoints().filter(c-> c>='a' && c<='z').count();
}

回答by Niraj Sonawane

java 8

爪哇 8

private static long countUpperCase(String inputString) {
        return inputString.chars().filter((s)->Character.isUpperCase(s)).count();
    }

    private static long countLowerCase(String inputString) {
        return inputString.chars().filter((s)->Character.isLowerCase(s)).count();
    }

回答by malik arman

import java.io.*;
import java.util.*;
public class CandidateCode {
    public static void main(String args[] ) throws Exception {
         int count=0,count2=0,i;
        Scanner sc = new Scanner(System.in);
         String s = sc.nextLine();
         int n = s.length();
         for( i=0; i<n;i++){
             if(Character.isUpperCase(s.charAt(i)))
                 count++;
             if(Character.isLowerCase(s.charAt(i))) 
             count2++;
         }
             System.out.println(count);
             System.out.println(count2);
         }



}

回答by Mohammad

You can increase the readability of your code and benefit from some other features of modern Java here. Please use the Stream approach for solving this problem. Also, please try to import the least number of libraries. So, avoid using .* as much as you can.

您可以在此处提高代码的可读性并从现代 Java 的一些其他功能中受益。请使用Stream方法来解决这个问题。另外,请尝试导入最少数量的库。所以,尽量避免使用 .* 。

import java.util.Scanner;

public class q36 {
    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);
        System.out.println("Give a string ");
        String input = keyboard.nextLine();
        int numberOfUppercaseLetters =
                Long.valueOf(input.chars().filter(c -> Character.isUpperCase(c)).count())
                        .intValue();
        int numberOfLowercaseLetters =
                Long.valueOf(input.chars().filter(c -> Character.isLowerCase(c)).count())
                        .intValue();
        System.out.println("The lenght of the String is " + input.length()
                + " number of uppercase letters " + numberOfUppercaseLetters
                + " number of lowercase letters " + numberOfLowercaseLetters);
    }
}

Sample input:

样本输入:

saveChangesInTheEditor

保存编辑器中的更改

Sample output:

示例输出:

The lenght of the String is 22 number of uppercase letters 4 number of lowercase letters 18

字符串的长度为 22 大写字母个数 4 小写字母个数 18