Java技术问询:如何检查字符串参数中是否包含元音
检查字符串是否包含元音的代码修正
你的代码存在几个关键问题需要修正:
nome.contains('a','e','i','o','u')语法错误:String.contains()仅接受单个字符串/字符序列参数,无法直接传入多个字符。- 未处理大小写:示例字符串
Leonardo中的大写O会被你的小写元音数组遗漏,导致判断不准确。 - 注释行
nome.contains(vocali)同样无效,因为contains()不支持直接传入字符数组。
修正方案1:遍历元音数组检查
public class Main { public static void main(String[] args) { String nome = "Leonardo"; int lunghezza = nome.length(); char[] vocali = {'a', 'e', 'i', 'o', 'u'}; System.out.println("Lunghezza parola: " + lunghezza); if (lunghezza > 5) { System.out.println("E' una parola piu' lunga di 5 lettere"); } else if (lunghezza < 5) { System.out.println("E' una parola piu' corta di 5 lettere"); } else { // 补充长度等于5的分支 System.out.println("E' una parola di 5 lettere"); } // 转小写统一检查,避免大小写问题 String nomeLower = nome.toLowerCase(); boolean hasVowel = false; for (char v : vocali) { if (nomeLower.contains(String.valueOf(v))) { hasVowel = true; break; // 找到元音后立即停止遍历 } } if (hasVowel) { System.out.println("Contiene vocali"); } else { System.out.println("Non contiene vocali"); } } }
修正方案2:使用正则表达式(更简洁)
public class Main { public static void main(String[] args) { String nome = "Leonardo"; int lunghezza = nome.length(); System.out.println("Lunghezza parola: " + lunghezza); if (lunghezza > 5) { System.out.println("E' una parola piu' lunga di 5 lettere"); } else if (lunghezza < 5) { System.out.println("E' una parola piu' corta di 5 lettere"); } else { System.out.println("E' una parola di 5 lettere"); } // 正则匹配任意大小写的元音 if (nome.matches(".*[aeiouAEIOU].*")) { System.out.println("Contiene vocali"); } else { System.out.println("Non contiene vocali"); } } }
关键说明
- 方案1通过遍历元音数组逐个检查,转小写后可匹配所有大小写形式的元音,逻辑直观。
- 方案2用正则表达式
.*[aeiouAEIOU].*,直接匹配字符串中是否存在任意元音,写法更简洁。 - 补充了字符串长度等于5的分支,完善了原有的长度判断逻辑。
内容的提问来源于stack exchange,提问作者Emanuele Siragusa
相关产品推荐
相关产品推荐

