【问题标题】:Search a string for multiple letters at once一次在字符串中搜索多个字母
【发布时间】:2013-12-24 00:17:15
【问题描述】:

我需要在一个字符串中搜索四个字母单词末尾的元音。我可以做一个 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 类,我只能使用我们以前学过的东西。

【问题讨论】:

  • 一种类型:s.indexOf ('i') == 4 - 注意==
  • 那么您希望返回哪个索引?
  • 您可能想仔细研究一下正则表达式:vogella.com/articles/JavaRegularExpressions/article.html
  • 只需构建您的函数...将数组作为参数,并为输入数组中的每个元素返回一个索引数组(使用您建议的代码找到)。
  • s.lastIndexOf('i') == 3 对于 "kind" (false) 是正确的,尤其是 "hihi" (true) 从 0 开始计数。"aeiou".indexOf? s.charAt(3)?

标签: java string search indexof


【解决方案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】:

    正则表达式?我相信这行得通。 “任何 3 个单词字符后跟 e i 或 u。”

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

    好吧,如果你不能使用正则表达式,那么使用为什么不使用类似 EDIT: Modified to be inline with GaborSch's answer - 我的替代算法非常接近,但是使用 char 而不是创建另一个字符串是 WAY更好的!为 GaborSch 投上一票!)

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

    【讨论】:

    • 不幸的是,这是一门课,我只需要使用我们以前学过的东西,我们还没有达到。不过还是谢谢你的回答!
    • @user3033159 你学过数组和for循环吗,因为那是另一种方法。如果是上课,你也应该把它标记为作业。
    • 或者你学会了String方法,包括matches(String)
    • 会更好:if("aeiouAEIOU".indexOf(c) != -1)
    • @SajalDutta 是的!已经对其进行了更改并归功于 GaborSch。
    【解决方案3】:

    试试这个方法:

    char c = s.charAt(3);
    if("aeiou".indexOf(c) >= 0) {
        System.out.println("Found");
    } else {
        System.out.println("Not found");
    }
    

    诀窍是您选择第 4 个字符并在所有元音的字符串中搜索它

    这是一个无正则表达式的单行解决方案。

    【讨论】:

    • 应该是 s.charAt(3) 因为它是一个四个字母的单词。
    【解决方案4】:

    这是String#matches(String) 的工作和一个合适的正则表达式:

    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 */
    }
    

    【讨论】:

      猜你喜欢
      • 2012-03-30
      • 2021-05-17
      • 1970-01-01
      • 2020-06-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-28
      相关资源
      最近更新 更多