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



你,所以我试着做一个程序,可以从用户输入字符串,例如:"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))){
            }
        }
    }
}

只需创建计数器,当发现小写或大写字母时增加,如下所示:

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

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

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

您可以尝试以下代码:

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

使用正则表达式:

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

}

可以提高代码的可读性,并受益于现代Java的一些其他特性。请使用流方法来解决这个问题。此外,请尽量导入最少数量的库。所以,尽量避免使用。*。

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

您只需在内容上循环并使用Character特性来测试它。我使用真实的码点,所以它支持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ßabc0uD801uDC00");
      // 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计数为小写(没有大写变体),并将特殊的补充代码点(两个代码单元/长字符)计数为大写。该数字将被计算为"other"。

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

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

相关内容

  • 没有找到相关文章

最新更新