[英]Refactor this Java code checking if a String contains any of these possibilities?
我需要检查一个字符串是否不包含任何这些字符串的可能性:
MNC BRA LEB MAR RVC WAY GLZ WWW HYB
我目前的代码:
if(selectedLocation.equals("OTH"))
{
if(!currentClassLocation.equals("MNC") &&
!currentClassLocation.equals("BRA") &&
!currentClassLocation.equals("LEB") &&
!currentClassLocation.equals("MAR") &&
!currentClassLocation.equals("RVC") &&
!currentClassLocation.equals("WAY") &&
!currentClassLocation.equals("GLZ") &&
!currentClassLocation.equals("WWW") &&
!currentClassLocation.equals("HYB"))
{
//Awesome, I need this string! I operate on it here.
}
}
长话短说,我不能使用for-loop。 有没有办法我可以检查字符串是否包含任何这些没有迭代?
使用HashSet
:
Set<String> invalidSequences = new HashSet<String>();
invalidSequences.add("MNC");
invalidSequences.add("BRA");
invalidSequences.add("LEB");
// Remaining sequences ...
if (!invalidSequences.contains(currentClassLocation)) {
// Awesome, I need this string...
}
尝试将这些字符串添加到Set然后使用包含O(c)的包含查找:
public class Filter {
Set<String> exclusionSet = new HashSet<String>();
public Filter( String... excludes ) {
for( String exclusion : excludes ) {
exclusionSet.add( exclusion );
}
}
public boolean exclude( String src ) {
return exclusionSet.contains( src );
}
public static void main( String[] args ) {
Filter filter = new Filter( "MNC BRA LEB MAR RVC WAY GLZ WWW HYB".split(" ") );
for( String arg : args ) {
System.out.println( arg + " is excluded? " + filter.exclude( arg ) );
}
}
}
创建字符串的HashSet,并执行O(1)检查以查看当前类位置是否存在于字符串集中。
尝试使用此变体(使用您的字符串):
Pattern pattern = Pattern.compile("(.*(AIN|BIN|CIN|Blam).*)*");
Matcher matcher = pattern.matcher(string_to_test);
在这里测试java正则表达式模式: Java Regex Tester
如果你想使用for循环,你可以简单地使用一个变量
String[] data = {"BRA","LEB","MAR","RVC","WAY","GLZ","WWW","HYB"};
if(selectedLocation.equals("OTH"))
{
boolean chk = false;
for(int i = 0; i < data.length; i++)
chk |= currentClassLocation.equals(data[i]);
if(!chk){
//Awesome, I need this string! I operate on it here.
}
}
如果您不想手动添加要设置的数据,也可以使用此选项。
import java.util.Arrays;
public class StringFind {
public static void main(String[] args) {
String stringtotest = "MNC";
String dataString = "MNC BRA LEB MAR RVC WAY GLZ WWW HYB";
String[] dataArray= dataString.split(" ");
Arrays.sort(dataArray); // You can omit this if data is already sorted.
if(Arrays.binarySearch(dataArray, stringtotest)<0){
System.out.println("Does not Exists");
}else{
System.out.println("Exists");
}
}
}
使用配置文件,以便无效序列列表变得可配置。 因为这是最神奇的一点,魔术字母组合系列。 将它移动到一组并没有帮助。
使用字符串数组:
String[] arr = {"MNC", "BRA", "LEB", "MAR", "RVC", "WAY", "GLZ", "WWW", "HYB"};
List list = Arrays.asList(arr);
if (!list.contains(currentClassLocation)) {
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.