题解 | #统计字符#

统计字符

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

import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern;

public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in);

    while(sc.hasNextLine()) {
    // Use regex to judge if the character is letter digigt or another
        java.lang.String regexLetter = "[a-zA-Z]";
        Pattern rl = Pattern.compile(regexLetter);
        java.lang.String regexDigit = "[0-9]";
        Pattern rd = Pattern.compile(regexDigit);
        java.lang.String regexWhiteSpace = "[\\s]";
        Pattern rws = Pattern.compile(regexWhiteSpace);
        char[] chars = sc.nextLine().toCharArray();
        int isLetter = 0, isDigit = 0, isWhiteSpace = 0, isAnother = 0;
        for(int i = 0; i < chars.length; i++) {
            if(rl.matcher(Character.toString(chars[i])).matches()) {
                isLetter++;
            } else if(rd.matcher(Character.toString(chars[i])).matches()) {
                isDigit++;
            } else if (rws.matcher(Character.toString(chars[i])).matches()) {
                isWhiteSpace++;
            } else {
                isAnother++;
            }
        }
        System.out.println(isLetter);
        System.out.println(isWhiteSpace);
        System.out.println(isDigit);
        System.out.println(isAnother);
    }
}

}

全部评论

相关推荐

11-15 17:19
湖南大学 Java
成果成果成果果:这是哪个公司的hr,这么离谱吗,我没见过用性别卡技术岗的,身边女性同学拿大厂offer的比比皆是
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务