题解 | #统计字符#

统计字符

http://www.nowcoder.com/practice/539054b4c33b4776bc350155f7abd8f5

Java 利用正则表达式

import java.util.*;
public class Main {
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            while(sc.hasNextLine()) {
                String str = sc.nextLine();
                String str1 = str.replaceAll("[^a-zA-Z]", "");
                String str2 = str.replaceAll("[^ ]", "");
                String str3 = str.replaceAll("[^0-9]", "");
                String str4 = str.replaceAll("[a-zA-Z0-9 ]", "");
                System.out.println(str1.length());
                System.out.println(str2.length());
                System.out.println(str3.length());
                System.out.println(str4.length());
            }
        }
}
全部评论
String s = new Scanner(System.in).nextLine(); //利用正则表达式,替换replaceAll(删除)别的。剩下的就是要求的长度 System.out.println(s.replaceAll("[^a-zA-Z]","").length()); System.out.println(s.replaceAll("\\S","").length()); System.out.println(s.replaceAll("\\D","").length()); System.out.println(s.replaceAll("[\\s\\da-zA-Z]","").length());
1 回复 分享
发布于 2022-07-05 20:01
还是正则表达式帅,我这个写的非常丑陋 public static void main(String[] args) { Scanner in = new Scanner(System.in); while (in.hasNext()) { String str = in.nextLine(); str = str.toLowerCase(); String engCh = "abcdefghijklmnopqrstuvwxyz"; String figCh = "0123456789"; String space = " "; int countEng = 0; int countFig = 0; int countSpace = 0; int elseCh = 0; for (int i = 0; i < str.length(); i++) { if (engCh.contains(Character.toString(str.charAt(i)))) { countEng++; } else if (figCh.contains(Character.toString(str.charAt(i)))) { countFig++; } else if (space.contains(Character.toString(str.charAt(i)))) { countSpace++; } else { elseCh++; } } System.out.println(countEng); System.out.println(countSpace); System.out.println(countFig); System.out.println(elseCh); } }
点赞 回复 分享
发布于 2022-10-17 18:40 广东

相关推荐

这算盘打的
程序员小白条:都这样的,都是潜规则,你自己说可以实习一年就行了,实习可以随便跑路的
点赞 评论 收藏
分享
程序员小白条:这比例牛逼,750:1
点赞 评论 收藏
分享
06-25 16:25
梧州学院 Java
愿汐_:项目介绍那么长,然而你做了啥就一句话?
点赞 评论 收藏
分享
评论
22
1
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务