java - 如何使用Java计算单词中的音节?
问题描述
我正在开发一个学生项目,需要编写一个函数来计算单词中的音节。该函数类似于 long countSyllables(String word)。
如何使用Java计算单词中的音节?有什么建议么?
提供的规则是:
要计算音节的数量,您应该使用字母 a、e、i、o、u、y 作为元音。
计算单词中元音的数量。
不计算双元音(例如,“rain”有 2 个元音但只有 1 个音节)
如果单词中的最后一个字母是“e”,则不要将其视为元音(例如,“side”是 1 个音节)
如果最后证明这个词包含 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());
}
解决方案
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
);
}
推荐阅读
- javascript - Chrome平滑滚动和requestAnimationFrame?
- python - Check if values of a column is in another column array in a pandas dataframe
- python-3.x - Python3 - 将嵌套列表变成可读的字符串或表格
- php - 在 symfony 中集成 Gitlab 提供身份验证问题
- android - 将数据显示到自定义 listView 的问题
- vue.js - 添加路径时,作为子域的 VueJS 应用程序抛出 404
- postgresql - 在 Postgres 中高效循环 VARIADIC
- c - C语言scanf中“%d”和“%d”的区别
- slack - 在 Slack 集成 RASA 聊天机器人中添加基于按钮的问题?
- javascript - 在javascript中将十进制数转换为百分比