/**
*
*/
package a.dw.fixbug01;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
/**
* @description 题目:从文件中读取一个字符串,分别统计出其英文字母、空格、数字和其它字符的个数
*/
public class ADwFixbug01Right {
/**
* 主函数,java运行的入口
* @param args
*/
public static void main(String[] args) {
// /a_dw_fixbug01_right/src/a/dw/fixbug01/a_dw_fixbug01.txt
String path = "E:\\dianwan\\a_dw_fixbug01_right\\src\\a\\dw\\fixbug01\\a_dw_fixbug01.txt";
String string = getStringFromFile(path);
handleString(string);
}
/**
*
* @param filepath 需要读取文件的路径
* @return 从文件读取出的字符串
*/
public static String getStringFromFile(String filepath) {
File file = new File(filepath); //定义一个file对象,用来初始化FileReader
FileReader reader;
try {
reader = new FileReader(file);
BufferedReader bReader = new BufferedReader(reader);
StringBuilder sb = new StringBuilder();
String s = "";
while ((s =bReader.readLine()) != null) {
sb.append(s);
}
bReader.close();
String str = sb.toString();
System.out.println(str );
return str;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "";
}
/**
* 用于处理文件中读取出的字符串数据,统计出其英文字母、空格、数字和其它字符的个数
* @param string 需要处理的字符串
*/
public static void handleString(String string) {
int num = 0;// 数字的个数
int letter = 0;// 字母的个数
int space = 0;// 空格的个数
int others = 0;// 其他的个数
// 把字符串里面的值赋值给一个字符型数组
char[] arr = string.toCharArray();
// 遍历字符串里面的所有值
for (int i = 0; i < arr.length; i++) {
if (arr[i] >= 48 && arr[i] <= 57) {// 字符是数字
num++;
} else if ((arr[i] >= 65 && arr[i] <= 90)
|| (arr[i] >= 97 && arr[i] <= 122)) {
letter++;
} else if (arr[i] == 32) {
space++;
} else {
others++;
}
}
System.out.println("数字:" + num + "个,字母:" + letter + "个,空格:" + space
+ "个,其他:" + others + "个");
}
}
基础编程
猜你喜欢
转载自blog.csdn.net/qq_39150192/article/details/82594138
今日推荐
周排行