Как проверить, все ли буквы / символы в строке находятся в массиве символов - PullRequest
0 голосов
/ 24 октября 2018

Как мне проверить, содержит ли строка только буквы из определенного массива символов

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++;
        }
    }
}

Ответы [ 7 ]

0 голосов
/ 24 октября 2018

Один из способов - преобразовать массив 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;
    }
}
0 голосов
/ 24 октября 2018
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
}
0 голосов
/ 24 октября 2018

Вы можете использовать containsAll из List

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
0 голосов
/ 24 октября 2018

Изменить код для использования регулярного выражения будет проще всего:

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++;
            }
        }
    }
}
0 голосов
/ 24 октября 2018

Используя пакет Java Arrays, просто проверьте, находится ли символ в массиве f char или нет.Если хотя бы один символ в строке недоступен в массиве 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++;
        }
    }
}
}
0 голосов
/ 24 октября 2018

Если это так, вы проверяете каждый символ строки на каждый символ массива символов, но это займет 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++;
        }
    }
}
0 голосов
/ 24 октября 2018

Вот мой код, может быть, он может вам помочь:

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;
}
...