首页 > 解决方案 > 如何使用Java计算单词中的音节?

问题描述

我正在开发一个学生项目,需要编写一个函数来计算单词中的音节。该函数类似于 long countSyllables(String word)。

如何使用Java计算单词中的音节?有什么建议么?

提供的规则是:

  1. 要计算音节的数量,您应该使用字母 a、e、i、o、u、y 作为元音。

  2. 计算单词中元音的数量。

  3. 不计算双元音(例如,“rain”有 2 个元音但只有 1 个音节)

  4. 如果单词中的最后一个字母是“e”,则不要将其视为元音(例如,“side”是 1 个音节) 

  5. 如果最后证明这个词包含 0 个元音,那么认为这个词是 1 个音节的。

我已经编写了该函数,但我认为它不是最佳的。所以我只是想看看其他可能的解决方案。如果有的话。

任务的完整描述:https ://hyperskill.org/projects/39/stages/208/implement

当前实施:

public static int countSyllables(final String word) {
    return max(1, word.toLowerCase()
            .replaceAll("e$", "")
            .replaceAll("[aeiouy]{2}", "a")
            .replaceAll("[^aeiouy]", "")
            .length());
}

标签: javaregexstringoptimization

解决方案


    public static int countSyllables(final String word) {
        return max(1, word.toLowerCase()
                    //in words that end with "e" replace 
                    //"e" with ""
                    .replaceAll("e$", "") //e.g base=bas
                    //when two vowels appear together, 
                    //replace them with "a" 
                    .replaceAll("[aeiouy]{2}", "a") //e.g you == au, 
                    //beautiful==bautiful
                    //again, when two vowels appear together, 
                    //replace them with "a" 
                    .replaceAll("[aeiouy]{2}", "a") //e.g au == a,
                    //bautiful==batiful
                    //replace any character that isn't aeiouy with ""
                    .replaceAll("[^aeiouy]", "") //e.g, batiful==aiu, 
                     //a == a
                    .length() //aiu == 3 syllables, a == 1 syllable
                );
        }

推荐阅读