You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java字符串处理:Diacritic去除方法封装及代码优化咨询

Java字符串处理代码优化:封装去变音符号方法与问题分析

原始代码

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String input = sc.nextLine();
        System.out.println(input);
        String[] sentences = input.split("\\. ");
        char[] reversedText = input.toCharArray();
        char[] normalizedText = input.toCharArray();
        int sentenceCount = 0;
        int vowelCount = 0;
        int consonantCount = 0;
        for (String sentence : sentences) {
            vowelCount = 0;
            consonantCount = 0;
            sentenceCount++;
            System.out.println(sentence);
            String[] words = sentence.split(" ");
            System.out.println("Number of words is " + words.length);
            String lowerCase = sentence.toLowerCase();
            char[] chars = lowerCase.toCharArray();
            System.out.println("Number of characters is " + sentence.length());
            for (char c : chars) {
                if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u' || c == 'y') {
                    vowelCount++;
                } else if (c == 'h' || c == 'k' || c == 'r' || c == 'd' || c == 't' || c == 'n') {
                    consonantCount++;
                }
            }
            System.out.println("Number of vowels is " + vowelCount);
            System.out.println("Number of consonants is " + consonantCount);
        }
        System.out.println(" ");
        System.out.println("Number of sentences is " + sentenceCount);
        for (int i = (reversedText.length) - 1; i >= 0; i--) {
            System.out.print(reversedText[i]);
        }
        System.out.println(" ");
        char[] diacritics = {'ě', 'š', 'č', 'ř', 'ž', 'ý', 'á', 'í', 'é', 'ú', 'ů', 'Ě', 'Š', 'Č', 'Ř', 'Ž', 'Ý', 'Á', 'Í', 'É', 'Ú', 'Ů' };
        char[] normal = {'e', 's', 'c', 'r', 'z', 'y', 'a', 'i', 'e', 'u', 'u', 'E', 'S', 'C', 'R', 'Z', 'Y', 'A', 'I', 'E', 'U', 'U' };
        for (int i = 0; i < normalizedText.length; i++) {
            char c = normalizedText[i];
            int index = -1;
            for (int j = 0; j < diacritics.length; j++) {
                if (c == diacritics[j]) {
                    index = j;
                    break;
                }
            }
            if (index != -1) {
                normalizedText[i] = normal[index];
            }
        }

        System.out.println(normalizedText);

    }
}

需求说明

我正在进行Java字符串处理开发,上述代码已实现分句、统计词数/字符数/元音辅音数、反转文本、去除Diacritic(变音符号)的功能,但去除Diacritic的逻辑为手动实现未封装为方法。请演示如何将该逻辑封装为方法,并指出当前代码中存在的问题。


一、封装去变音符号方法后的代码

将去变音符号的逻辑抽离为独立方法,提升代码复用性和可读性:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String input = sc.nextLine();
        System.out.println(input);
        
        String[] sentences = input.split("\\. ");
        int sentenceCount = 0;
        
        for (String sentence : sentences) {
            sentenceCount++;
            System.out.println(sentence);
            
            // 统计词数
            String[] words = sentence.split(" ");
            System.out.println("Number of words is " + words.length);
            
            // 统计字符数
            System.out.println("Number of characters is " + sentence.length());
            
            // 统计元音和辅音
            int vowelCount = 0;
            int consonantCount = 0;
            String lowerCase = sentence.toLowerCase();
            for (char c : lowerCase.toCharArray()) {
                if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u' || c == 'y') {
                    vowelCount++;
                } else if (Character.isLetter(c) && !(c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u' || c == 'y')) {
                    consonantCount++;
                }
            }
            System.out.println("Number of vowels is " + vowelCount);
            System.out.println("Number of consonants is " + consonantCount);
        }
        
        System.out.println("\nNumber of sentences is " + sentenceCount);
        
        // 反转文本
        String reversedText = new StringBuilder(input).reverse().toString();
        System.out.println(reversedText);
        
        // 调用封装的方法去除变音符号
        String normalizedText = removeDiacritics(input);
        System.out.println(normalizedText);
        
        sc.close();
    }
    
    // 封装的去除变音符号方法
    private static String removeDiacritics(String input) {
        char[] diacritics = {'ě', 'š', 'č', 'ř', 'ž', 'ý', 'á', 'í', 'é', 'ú', 'ů', 'Ě', 'Š', 'Č', 'Ř', 'Ž', 'Ý', 'Á', 'Í', 'É', 'Ú', 'Ů'};
        char[] normalChars = {'e', 's', 'c', 'r', 'z', 'y', 'a', 'i', 'e', 'u', 'u', 'E', 'S', 'C', 'R', 'Z', 'Y', 'A', 'I', 'E', 'U', 'U'};
        
        StringBuilder sb = new StringBuilder(input);
        for (int i = 0; i < sb.length(); i++) {
            char currentChar = sb.charAt(i);
            for (int j = 0; j < diacritics.length; j++) {
                if (currentChar == diacritics[j]) {
                    sb.setCharAt(i, normalChars[j]);
                    break;
                }
            }
        }
        return sb.toString();
    }
}

二、当前代码存在的问题

1. 分句逻辑缺陷

  • 仅通过split("\\. ")分割句子,若句号后无空格(如Hello.World)、句子以感叹号/问号结尾,或遇到缩写(如Mr. Smith)时,都会导致分句错误。

2. 词数统计不准确

  • 使用split(" ")分割单词,连续空格会生成空字符串,被误统计为单词(如Hello World会被算成3个单词)。

3. 元音辅音统计不完整

  • 仅统计了特定的6个元音和6个辅音,遗漏了绝大多数辅音(如b、c、f等);未排除非字母字符(如数字、标点),逻辑上应先判断是否为字母再分类统计。

4. 反转文本实现冗余

  • 手动遍历char数组反转,可直接使用StringBuilder.reverse()方法,代码更简洁高效。

5. 去变音符号原始实现的问题

  • 手动维护两个字符数组,新增变音符号时需同步修改两个数组,易出错;仅支持特定的变音符号,无法覆盖其他语言的字符;直接修改原char数组,灵活性差。

6. 变量作用域不合理

  • vowelCount和consonantCount在循环外声明,实则每次循环都会重置,应在循环内部声明,缩小作用域。

7. 输入处理不完善

  • 仅读取一行输入,无法处理多行文本;未考虑输入为空的情况,可能导致后续逻辑报错。

内容的提问来源于stack exchange,提问作者QuackGaming1220

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 05:27:37