Java文本分析:统计字母、替换单词、提取数字
import java.util.Scanner;
public class TextAnalysis { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int letterCount = 0; StringBuilder textBuilder = new StringBuilder(); while (true) { String line = scanner.nextLine(); if (line.equals('end')) { break; } textBuilder.append(line).append(' '); for (char c : line.toCharArray()) { if (Character.isLetter(c)) { letterCount++; } } } String text = textBuilder.toString(); System.out.println('英文字母个数:' + letterCount); System.out.println('将所有单词the替换为a后的结果:'); String replaced = text.replaceAll('\bthe\b', 'a'); System.out.println(replaced); System.out.println('数字串:'); String[] words = text.split('\s+'); for (String word : words) { if (word.matches('\d+')) { System.out.println(word); } } } }
原文地址: https://www.cveoy.top/t/topic/ne8U 著作权归作者所有。请勿转载和采集!