java实现统计字符串中数字中文字母各自总数

package com.example.phone.controller;

public class test6 {
    public static void main(String[] args) {
        String str="agnjgALKGj24249gajl134我爱你新新5398gjAKg我爱你";
        int a=0;
        int b=0;
        int c=0;
        for (int i=0;i<str.length();i++){
            char d=str.charAt(i);
            if (d >= '0'&& d<= '9'){
                a++;
            }else if (d >= 'a'&& d<= 'z'||d >= 'A'&&d <= 'Z'){
                b++;
            }else {
                c++;
            }

        }
        System.out.println("数字:"+a+"字母:"+b+"中文:"+c);
    }

}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
您可以使用以下代码来实现统计任意一个字符串的英文单词总数、最长单词的长度、最短单词的长度、单词的平均长度: ```java public static void analyzeWords(String str) { if (str == null || str.isEmpty()) { System.out.println("The input string is null or empty."); return; } // Split the input string into an array of words String[] words = str.split("\\s+"); int wordCount = words.length; int shortestWordLength = Integer.MAX_VALUE; int longestWordLength = 0; int totalWordLength = 0; // Iterate over each word to determine its length for (String word : words) { // Remove any non-alphabetic characters from the word word = word.replaceAll("[^a-zA-Z]", ""); if (word.isEmpty()) { // Skip over any empty words continue; } int wordLength = word.length(); totalWordLength += wordLength; if (wordLength < shortestWordLength) { shortestWordLength = wordLength; } if (wordLength > longestWordLength) { longestWordLength = wordLength; } } double averageWordLength = (double) totalWordLength / wordCount; // Output the results System.out.println("Word count: " + wordCount); System.out.println("Shortest word length: " + shortestWordLength); System.out.println("Longest word length: " + longestWordLength); System.out.println("Average word length: " + averageWordLength); } ``` 在上述代码,我们首先将输入字符串按照空格分割成一个单词数组,然后遍历每一个单词。对于每一个单词,我们先将其剔除掉非字母字符,然后统计其长度。同时,我们也记录下最短单词的长度、最长单词的长度和所有单词的总长度。最后,我们根据这些统计数据计算出单词的平均长度,并将所有结果输出到控制台。 请注意,本代码假定输入字符串的单词均为英文单词,如果有其他语言的单词或者标点符号,可能需要进行一些额外的处理。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值