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

时间:2014-08-10 02:25:54

标签: java string character-class

哟,所以我试图创建一个可以从用户那里获取字符串输入的程序:“ONCE UPON a time”然后报告该字符串包含多少个大写和小写字母:

输出示例:该字符串有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))){

            }
        }
    }
}

8 个答案:

答案 0 :(得分:17)

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

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);

答案 1 :(得分:4)

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();
}

答案 2 :(得分:4)

java 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();
    }

答案 3 :(得分:1)

您可以尝试以下代码:

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);
    }
}

答案 4 :(得分:0)

使用正则表达式:

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;
}

答案 5 :(得分:0)

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);
         }



}

答案 6 :(得分:0)

您可以在这里增加代码的可读性,并从现代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);
    }
}

示例输入

saveChangesInTheEditor

示例输出:

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

答案 7 :(得分:-1)

您只需循环遍历内容并使用“角色”功能对其进行测试。我使用真正的代码点,因此它支持Unicode的补充字符。

当处理代码点时,索引不能简单地加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);
}

对于此示例,结果将是:

// 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

它将德语sharp-s统计为小写(没有大写变体)和特殊补充代码点(两个codeunits / char long)作为大写。该号码将被计为&#34;其他&#34;。

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

有关您需要关注代码点和单位的原因的背景知识,请查看:http://www.joelonsoftware.com/articles/Unicode.html