【问题标题】:How to check if the letters/chars in a string are all found in a char array如何检查字符串中的字母/字符是否都在字符数组中找到
【发布时间】:2019-03-28 08:05:42
【问题描述】:

如何检查一个字符串是否只包含来自某个字符数组的字母

import java.util.*;

public class Main {

    static char[] f = {'q','w','e','r','t','y','u','i','o','p'};
    static char[] s = {'a','s','d','f','g','h','j','k','l'};
    static char[] t = {'z','x','c','v','b','n','m'};

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int count = 0;
        for(int i = 0; i < n; i++) {
            String str = sc.nextLine();
            if(string only contains letters from array f) count++;
        }
    }
}

【问题讨论】:

  • 为什么不使用字符串而不是字符数组来表示 f、s、t?然后你可以使用 contains 方法来解决你的问题。
  • int count = Stream.generate(sc::nextLine).limit(sc.nextInt()).filter(s -&gt; s.chars().map(new String(f)::indexOf).allMatch(i -&gt; i &gt; -1)).count();
  • @shmosel 什么?我真的不明白。
  • 提示:两个循环,一个在 str 中的字符上,在那个里面,另一个在数组 f 中的字符上
  • @shmosel 一定有更易读的方式

标签: java arrays string char


【解决方案1】:

这是我的代码,也许它可以帮助你:

public static boolean checkIfStringContainsLettersFromArray(String str, char [] arr) {
    String arrString = new String(arr);

    for(int i = 0; i < str.length(); i++) {
        if(arrString.indexOf(str.charAt(i)) < 0) return false; 
    }
    return true;
}

【讨论】:

  • String arrString = new String(arr);
  • 哦,是的,谢谢 shmosel!我按照你的建议编辑了我的答案
  • 根据字符串和 char[] 的长度,为白名单创建哈希集并调用 contains 可能更有效。
【解决方案2】:

如果是这种情况,您将检查 String 的每个字符与 char 数组的每个字符,但这需要 2 遍。 如果您想要更高效,请将 char 数组中的所有元素放入 Set 中,它的恒定时间来检查其中的 char,因此只需要一次 String 传递,如下所示:

public class Main {

    static char[] f = {'q','w','e','r','t','y','u','i','o','p'};
    static char[] s = {'a','s','d','f','g','h','j','k','l'};
    static char[] t = {'z','x','c','v','b','n','m'};
    //showing one example
    HashSet<Character> fs = new HashSet();
    fs.addAll(f);
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int count = 0;
        for(int i = 0; i < n; i++) {
            String str = sc.nextLine();
            int flag = 0;
            for (int l =0;l<str.length();l++){
                if(fs.contains(str.charAt(l)) == false){ flag = 1; break;   }
            }
            if (flag == 0){count++}
            //if(string only contains letters from array f) count++;
        }
    }
}

【讨论】:

    【解决方案3】:

    使用 java Arrays 包,只需检查字符是否在 f char 数组中。如果字符串中至少有 1 个字符在 f char 数组中不可用,您的程序将停止处理当前字符串并继续处理下一个字符串。

    import java.util.*;
    import java.util.Arrays;
    
    public class Main {
    static char[] f = {'q','w','e','r','t','y','u','i','o','p'};
    static char[] s = {'a','s','d','f','g','h','j','k','l'};
    static char[] t = {'z','x','c','v','b','n','m'};
    
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int count = 0;
        for(int i = 0; i < n; i++) {
            String str = sc.nextLine();
            char[] chars = str.toCharArray();
            int j = 0;
            for(; j < chars.length; j++){
               if(!Arrays.asList(f).contains(chars[j])){
                   break;
               }
            }
            if(j == chars.length){
                count++;
            }
        }
    }
    }
    

    【讨论】:

      【解决方案4】:

      更改代码以使用正则表达式是最简单的:

      public class Main {
          private static final String f = "[qwertyuiop]*";
          private static final String s = "[asdfghjkl]*";
          private static final String t = "[zxcvbnm]*";
      
          public static void main(String[] args) {
              Scanner sc = new Scanner(System.in);
              int n = sc.nextInt();
              int count = 0;
              for (int i = 0; i < n; i++) {
                  String str = sc.nextLine();
                  if (str.matches(f)) {
                      count++;
                  }
              }
          }
      }
      

      【讨论】:

      • 会是最简单的 - 也许不是
      【解决方案5】:

      您可以使用containsAllList

      char arr[] = "scarywombat".toCharArray();
      List<Character> limit = new ArrayList<Character>();
      List<Character> input = new ArrayList<Character>();
      
      for (char c : arr) {
          limit.add (c);
          input.add (c);
      }
      
      System.out.println(limit);
      System.out.println(input);
      System.out.println(limit.containsAll(input));
      
      //add extra char
      input.add('Z');
      System.out.println(limit);
      System.out.println(input);
      System.out.println(limit.containsAll(input));
      

      输出

      [s, c, a, r, y, w, o, m, b, a, t]
      [s, c, a, r, y, w, o, m, b, a, t]
      true
      [s, c, a, r, y, w, o, m, b, a, t]
      [s, c, a, r, y, w, o, m, b, a, t, Z]
      false
      

      【讨论】:

        【解决方案6】:

        一种方法是将 char 数组转换为一个集合并测试字符串中的任何字符是否包含数组中没有的任何字符:

        import com.google.common.primitives.Chars;
        
        import java.util.HashSet;
        import java.util.Scanner;
        import java.util.Set;
        
        public class Main {
        
            static char[] f = {'q','w','e','r','t','y','u','i','o','p'};
            static char[] s = {'a','s','d','f','g','h','j','k','l'};
            static char[] t = {'z','x','c','v','b','n','m'};
        
            public static void main(String[] args) {
                Scanner sc = new Scanner(System.in);
                int n = sc.nextInt();
                int count = 0;
        
                for(int i = 0; i < n; i++) {
                    String str = sc.nextLine();
                    if(containsOnly(str, f)) count++;
                }
            }
        
            private static boolean containsOnly(String stringToSearch, char[] theOnlyChars) {
        
                Set<Character> collect = new HashSet<>(Chars.asList(theOnlyChars));
        
                for (int i = 0; i < stringToSearch.length(); i++) {
                    char c = stringToSearch.charAt(i);
                    if (!collect.contains(c)) {
                        return false;
                    }
                }
        
                return true;
            }
        }
        

        【讨论】:

          【解决方案7】:
          static Pattern f = toPattern(new char[]{'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p'});
          static Pattern s = toPattern(new char[]{'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l'});
          static Pattern t = toPattern(new char[]{'z', 'x', 'c', 'v', 'b', 'n', 'm','\n'});
          
          private static Pattern toPattern(char[] arr) {
              return Pattern.compile(String.format("[%s]*", new String(arr)), Pattern.MULTILINE);
          }
          
          private static boolean checkIfStringContainsLettersFromArray(String str, Pattern whitelist) {
              return whitelist.matcher(str).matches();
          }
          
          public static void main(String[] args) {
              System.out.println(checkIfStringContainsLettersFromArray("zxzxzxzxcvbnmxzxz", t)); //true
              System.out.println(checkIfStringContainsLettersFromArray("zxzxzxzxa ", t)); //false
          }
          

          【讨论】:

            猜你喜欢
            • 2014-01-01
            • 2017-10-18
            • 2011-12-24
            • 2019-03-31
            • 2020-07-06
            • 1970-01-01
            • 1970-01-01
            • 2013-08-10
            • 1970-01-01
            相关资源
            最近更新 更多