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

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 10:26:12