[英]Java: verify if a string is formed only by letters from another string
I want to make a function who have String a and String b. 我想做一个具有String a和String b的函数。 I want to verify if String a is formed only by characters/letters from String b.
我想验证字符串a是否仅由字符串b中的字符/字母组成。
Ex: 例如:
String a="abz"; String b="abecxe";
The result is false, because String b is not contain 'z' from String a. 结果为假,因为字符串b不包含字符串a中的“ z”。
Thank you! 谢谢!
Assuming you can write code to protect against null/invalid input: 假设您可以编写代码以防止输入无效/无效:
return b.replaceAll("["+a+"]", "").length() == 0;
As pointed out this will fail for arbitrary Strings. 如前所述,这对于任意字符串都将失败。
for (int i = 0; i < b.length(); i++) {
if (!a.contains(b.substring(i, i + 1)) {
return false;
}
}
return true;
Again, you write the validation. 同样,您编写验证。
One very straightforward way to do this is to write a method that converts a String
into a set of characters, then take advantage of the removeAll
method of the Set
interface. 一种非常简单的方法是编写一个将
String
转换为字符集的方法,然后利用Set
接口的removeAll
方法。 You might need the Apache ArrayUtils
class to convert the char[]
from your String
into a Character[]
. 您可能需要Apache
ArrayUtils
类将char[]
从String
转换为Character[]
。
It could look like this. 它可能看起来像这样。
public static boolean containsOnlyCharactersFrom(String first, String second) {
return charactersIn(first).removeAll(charactersIn(second)).isEmpty();
}
private static Set<Character> charactersIn(String argument) {
Character[] characterArray = ArrayUtils.toObject(argument.toCharArray());
return new HashSet<Character>(Arrays.asList(characterArray));
}
Thanks to all! 谢谢大家!
i solve the problem with String matching(i tried this method in the past but i was wrong): 我用字符串匹配解决了问题(我过去曾尝试过这种方法,但是我错了):
if ( a.matches("[" + b + "]+")) { label1.setText("The String a contains only letters from String b!"); } else { label2.setText("The String a contains more letters than String b!"); }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.