有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java一次在字符串中搜索多个字母

我需要在字符串中搜索四个字母单词末尾的元音。我可以做一个if-else树,逐个搜索每个字母,但我想简化一下

您通常通过以下方式搜索信件:

String s = four
if (s.indexOf ('i') = 4)
  System.out.println("Found");
else
  System.out.println("Not found");

我是否可以用以下内容替换indexOf的参数:

s.indexOf ('a','e','i','o','u')

这会让一切变得容易得多

不幸的是,我不能使用Regexp类,而且我只需要使用我们之前学到的东西


共 (3) 个答案

  1. # 1 楼答案

    String s = "FOUR"; // A sample string to look into
    String vowels = "aeiouAEIOU"; // Vowels in both cases
    
    if(vowels.indexOf(s.charAt(3)) >= 0){ // The last letter in a four-letter word is at index 4 - 1 = 3
        System.out.println("Found!");
    } else {
        System.out.println("Not Found!");
    }
    
  2. # 2 楼答案

    正则表达式?我相信这是有效的。“后跟e i或u的任意3个单词字符。”

        Pattern p = Pattern.compile("\\w{3}[aeiou]?");
        String test = "mike";
        System.out.println("matches? " + p.matcher(test).matches());
    

    好吧,如果你不能使用正则表达式,那么为什么不使用像EDIT:Modified这样的东西来与GaborSch的答案保持一致——我的替代算法非常接近,但是使用char而不是创建另一个字符串要好得多!向加博什投一票

        if(someString.length() == 4){
            char c = someString.charAt(3);
    
            if("aeiou".indexOf(c) != -1){
                 System.out.println("Gotcha ya!!");
            }
        }
    
  3. # 3 楼答案

    这是^{}的作业,也是一个合适的正则表达式:

    if (s.matches(".*[aeiou]$")) {
        /* s ends with a vowel */
    }
    

    如果不允许使用正则表达式,可以为此定义函数:

    static boolean endsWithVowel(String str) {
        if (str == null || str.length() == 0) {  /* nothing or empty string has no vowels */
            return false;
        }
        return "aeiou".contains(str)             /* str is only vowels */
            || endsWithVowel(str.substring(1));  /* or rest of str is only vowels */
    }