gpt4 book ai didi

java - 如何判断一个单词是否以元音开头

转载 作者:行者123 更新时间:2023-12-02 11:17:21 25 4
gpt4 key购买 nike

我需要找出文件中的单词是否以元音开头,我知道该怎么做,但我的 if 语句效率很低。我必须将分词器中的单词放入 arrayList,然后使用 if 语句使用 .startsWith() 5 次不同的时间来解释每个元音。有没有可能更快的方法来做到这一点?

    while (s.hasMoreTokens()){
word = s.nextToken();
list.add(word);
if (list.get(i).startsWith("a")||list.get(i).startsWith("e")||list.get(i).startsWith("i")||list.get(i).startsWith("o")||list.get(i).startsWith("u")) {
vowelCount++;
}
}

最佳答案

那么,您可能有 3 个不同的目标:

1) 语言是否敏感?如果是这样,元音的概念就很棘手,并且可能会被委托(delegate)给一些国际化(i18n)烦人的东西,我不会在这里介绍。

2) 代码紧凑,但不一定更快:

boolean startWithVowel(String word) {
return "eaiouEAIOU".indexOf(word.charAt(0)) >=0
}

3)快速但冗长的代码:

boolean startWithVowel(String word) {

switch(word.charAt(0)) {
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
case 'A':
case 'E':
case 'I':
case 'O':
case 'U':
return true;
default:
return false;
}
}

//in class definition:
static final boolean[] vowels = new byte['u'+1];
static {
vowels['a'] = vowels['A'] = vowels['e'] = vowels['E'] = ..... = true;
}

boolean startWithVowel(String word) {
int index = word.chartAt(0);
return index<='u' && vowels[index]);
}

当然,请允许在某处进行健全性检查,例如 word.lenght>0 。(无论你做什么,如果担心速度,请避免使用正则表达式)

关于java - 如何判断一个单词是否以元音开头,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50177076/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com