【问题标题】:Comparing a char with multiple characters将一个字符与多个字符进行比较
【发布时间】:2014-09-18 14:38:21
【问题描述】:
for(int j=0 ; j<str.length() ; j++) {
    if(char[j]==(a||e||i||o||u))
        count++;
}

我知道(a||e||i||o||u) 的结果是布尔值,所以无法比较,但我们如何检查是否存在多个字符?

【问题讨论】:

  • 使用String.contains()

标签: java arrays if-statement char boolean


【解决方案1】:

这不是你想要的。请使用堆栈switch 声明:

for(int j = 0; j < str.length(); j++)
     switch(str.charAt(j)) {
         case 'a':
         case 'e':
         case 'i':
         case 'o':
         case 'u':
             count++;
     }

或者,由于我是正则表达式爱好者,这里有一个使用正则表达式的方法! :)

Matcher matcher = Pattern.compile("[aeiou]").matcher(str);
while(matcher.find())
    count++;

此代码有错误,稍后修复,thanks to user2980077

【讨论】:

  • 这是更快的方法。顺便说一句,这个问题是小事。
  • @Unihedron 老实说,我不确定 switch 语句是否在没有明确的 default: 案例的情况下跳到末尾,如果它没有找到匹配的案例 - 因为 switch 是仍然只是一个有组织的goto。如果是这样的话,那么我想它没有修复错误,但至少我缩进它很漂亮:D
【解决方案2】:

我建议使用String.contains() 并将每个搜索到的字符添加到字符串中。

private static final String SEARCH = "aeiou";

public static void main(String[] args) {
    char[] chars = new char[]{'a', 'b', 'A'};
    int count = 0;

    for (int i = 0; i < chars.length; i++) {
        if (SEARCH.contains((chars[i] + "").toLowerCase())) {
            count++;
        }
    }

    System.out.println(count);
}

输出为 2。(代码肯定可以优化)

这有三个好处:

  1. 添加要查找的新字符要容易得多。

  2. 此代码不区分大小写。 (删除toLowerCase()方法调用使其区分大小写)

  3. 避免使用“长” if/else 或 switch/case 块。

【讨论】:

    【解决方案3】:

    如果你使用类,你可以尝试使用正则表达式或简单字符串

    String s = "aeiouaeiou";//string to count
    int count = 0;
    for (int i = 0; i < s.length(); i++) {
    
      //One method
      if ("aeiou".indexOf( s.charAt(i) ) >= 0) {
        count++;
      }
    
      //Another one
      if (Character.toString( s.charAt(i) ).matches("[aeiou]")) {
        count++;
      }
    
    }
    

    【讨论】:

      【解决方案4】:

      聪明的正则表达式部门的另一个:

      count = str.replaceAll("[^aeiou]","").length();
      

      【讨论】:

      • @Unihedron 是的,如果count 在提问者的代码之前可能是非零并且他打算添加到已经存在的内容,+= 是正确的。
      【解决方案5】:

      如果我真的需要使用char[] 数组而不是String 实例,我总是使用Character 类和正则表达式。如果您不知道什么是正则表达式,您应该学习它们,因为它们在处理字符串时非常有用。也可以在Regexr练习。

      对于你的例子,我会使用这个:

      char[] data = "programming in Java is fun".toCharArray();
      int counter = 0;
      
      for(int i = 0; i<data.length; i++){
          if(Character.toString(data[i]).matches("[aeiou]")){
              counter++;
          }
      }
      
      System.out.println(counter); // writes: 8
      

      if 语句的作用基本上是创建一个包含当前字符的新 String 实例,以便能够使用 String 类中的方法。 boolean matches(String regex) 方法检查您的字符串是否满足regex 参数给出的条件。

      【讨论】:

        【解决方案6】:

        Java 8 的另一个:

        count = str.chars()
                   .filter(c -> c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u' )
                   .count();
        

        【讨论】:

          【解决方案7】:

          使用ListCharacter 的方法之一可能是:

          List<Character> vowels = List.of('a','e','i','o','u'); // pverloaded convenience factory method 
          for(int j=0 ; j < str.length() ; j++) {
              if(vowels.contains(char[j])) {
                  count++;
              }
          }
          

          【讨论】:

            【解决方案8】:

            这是一个使用扩展方法的解决方案。

            public static class Extensions
            {
                public static bool Compare(this char c, params char[] ar)
                {
                    foreach (var val in ar)
                        if (c == val)
                            return true;
                    return false;
                }
            }
            // use:
            
                public static void Main()
                {
                    var ans = 'c'.Compare('w', 's', 'c');
                }
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2020-09-03
              • 1970-01-01
              • 1970-01-01
              • 2012-09-10
              • 1970-01-01
              • 2021-03-04
              • 1970-01-01
              • 2018-05-29
              相关资源
              最近更新 更多