【发布时间】: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 -> s.chars().map(new String(f)::indexOf).allMatch(i -> i > -1)).count(); -
@shmosel 什么?我真的不明白。
-
提示:两个循环,一个在
str中的字符上,在那个里面,另一个在数组f中的字符上 -
@shmosel 一定有更易读的方式