前往小程序,Get更优阅读体验!
立即前往
发布
社区首页 >专栏 >统计字符数量

统计字符数量

作者头像
算法与编程之美
发布2023-01-03 18:43:24
发布2023-01-03 18:43:24
1K0
举报

1 问题

在编程中,我们会遇到需要统计一段字符中字符的数量的问题,我们该如何解决这些问题呢?

2 方法

我们可以利用ASKII编码再加上for循环和条件判断来进行转换,这样就可以分别计算出数字、字母、及其他字符的数量

package test;

import java.util.Scanner;

public class Work2 {

public static void main(String[] args) {

int word = 0;

int space= 0;

int num = 0;

int other = 0;

Scanner s = new Scanner(System.in);

System.out.println("请输入字符:");

String str = s.nextLine();

char[] arr = new char[str.length()];

for (int i = 0; i < str.length(); i++) {

char a = str.charAt(i);

if ((int) a >= 65 && (int) a <= 90 || (int) a >= 97 && (int) a <= 122) {

word++;

} else if ((int) a == 32) {

space++;

} else if ((int) a >= 48 && (int) a <= 57) {

num++;

} else {

other++;

}

}

System.out.println("英文字母有:" + word + "个");

System.out.println("空格有:" + space + "个");

System.out.println("数字有:" + num + "个");

System.out.println("其他字符:" + other + "个");

}

}

3 结语

针对如何计算字符串数量的问题,提出通过利用ASKII编码和循环判断的方法,通过java的编程实验,证明该方法是有效的,本文只是单纯对字母,数字及空格进行区分,之后还可以更加细节。例如大小写也进行区分。

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2022-10-16,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 算法与编程之美 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档