统计字符个数

题目:输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数。

这个比较简单,只要记住规律即可,代码如下:

import java.util.Scanner;


public class tongjizifugeshu {
	public static void main(String[] args) {
		int english = 0;
		int blank = 0;
		int digital = 0;
		int other = 0;
		char[] ch = null;
		
		Scanner shuru = new Scanner(System.in);
		System.out.println("请输入一串字符:");
		String s = shuru.nextLine();
		ch = s.toCharArray();
		
		for (int i = 0; i < ch.length; i++) {
			if (ch[i] >= '0' && ch[i] <= '9') {
				digital ++;
			}
			else if ((ch[i] >= 'a' && ch[i] <= 'z') || (ch[i] >= 'A' && ch[i] <= 'Z')) {
				english ++;
			}
			else if (ch[i] == ' ') {
				blank ++;
			}
			else {
				other ++;
			}
		}
		System.out.println("数字个数:" + digital);
		System.out.println("英文字母:" + english);
		System.out.println("空格字符:" + blank);
		System.out.println("其他字符:" + other);
	}
}

把题目再改进一下,输入一个目录中文档的行数,字符数,数字,空格数和其他

这里需要用到java的读文件方法,用readline把文件读取,这个是一次性读取一行,并且自动忽略了结尾的换行符,也就是说,如果你不在读完一行后强制换行,那么就输出的就是一行东西了。


具体代码如下:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;


public class duquwenjian {
	public static void main(String[] args) {
		try {
			readtxt();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	private static String readtxt() throws IOException {
		FileReader a = new FileReader("C:/Users/Administrator/Desktop/test/test.txt");
		BufferedReader br = new BufferedReader(a);
		
		String str = "";
		String r = br.readLine();
		
		while (r != null) {
			str += r + "\n";
			r = br.readLine();
		}
		
		try {
			char[] ch = readtxt().toCharArray();
			
			int line = 0;
			int zifu = 0;
			int blank = 0;
			int number = 0;
			int other = 0;
		
			for (int i = 0; i < ch.length; i ++){
				if (ch[i] == '\n') {
					line ++;
				}
				else if (ch[i] >= '0' && ch[i] <= '9') {
					number ++;
				}
				else if ((ch[i] >= 'a' && ch[i] <= 'z') || (ch[i] >= 'A' && ch[i] <= 'Z')) {
					zifu ++;
				}
				else if (ch[i] == ' ') {
					blank ++;
				}
				else {
					other ++;
				}
			}
			
			System.out.println("行数:" + line);
			System.out.println("数字:" + number);
			System.out.println("字母:" + zifu);
			System.out.println("空格数:" + blank);
			System.out.println("其他字符:" + other);
			System.out.println(readtxt());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 

		return "";
	}
	
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值