如何检查字符串是否包含指定字符以外的字符。(在 Java 中)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15150193/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check that a string contains characters other than those specified. (in Java)
提问by J.L.Louis
I have a program that asks the user to input a three character string. The string can only be a combination of a, b, or c.
我有一个程序,要求用户输入一个三个字符的字符串。字符串只能是 a、b 或 c 的组合。
How do I check if the string contains any other characters than those specified without doing a million conditional statements.
如何在不执行一百万条条件语句的情况下检查字符串是否包含指定字符以外的任何其他字符。
Pseudo example:
伪示例:
String s = "abq"
if (s.containsOtherCharacterThan(a,b,c))
System.exit(-1)
回答by Indigenuity
To look for characters that are NOT a, b, or c, use something like the following:
要查找不是 a、b 或 c 的字符,请使用如下所示的内容:
if(!s.matches("[abc]+"))
{
System.out.println("The string you entered has some incorrect characters");
}
回答by Pshemo
You can use regex and its character classes. Just invoke String#matches(String regex)
on string you want to check if it can be matched entirely by regex.
您可以使用正则表达式及其字符类。只需调用String#matches(String regex)
您想检查它是否可以完全由正则表达式匹配的字符串。
if (!s.matches("[abc]+")) {//..
This test should pass only strings that contains also other characters then specified in [
]
so "abq"
should pass it since it contains q
. Matches will check if s
contains only a
, b
, and c
characters. If not it will will return false
, and thanks to negation we will enter in if block.
此测试应仅通过还包含其他字符的字符串,然后在中指定,[
]
因此"abq"
应通过它,因为它包含q
. 比赛将检查是否s
只包含a
,b
和c
字符。如果不是,它将返回false
,并且由于否定,我们将进入 if 块。
回答by Warren Green
You could split the string into an array and loop through the input from there you could compare each character.
您可以将字符串拆分为一个数组并从那里循环输入,您可以比较每个字符。
public boolean containsOtherCharacter(String s, String a, String b, String c) {
String[] st = s.split("");
for(int x = 0; x < st.length; x++)
if (st[x].compareTo(a) != 0 && st[x].compareTo(b) != 0 && st[x].compareTo(c) != 0)
return true;
return false;
}
This will tell you if there are any other characters. If you would like to know which characters they are, you could insert each character into a HashMap where the key is the character and the value is the number of times it is used.
这将告诉您是否还有其他字符。如果您想知道它们是哪些字符,您可以将每个字符插入到一个 HashMap 中,其中键是字符,值是它被使用的次数。
回答by SudoRahul
You can use this regular expression:- [abc]+
.
您可以使用此正则表达式:- [abc]+
。
回答by jrajav
A way without regex would be to loop through the string and check each character, exiting if the character is anything but a, b, or c. There is no way to do it just with String.contains
没有正则表达式的一种方法是遍历字符串并检查每个字符,如果字符不是 a、b 或 c,则退出。没有办法只用 String.contains