I know this question is basic but I am looking for a less-clumsy approach to the following if statement:
if ((sOne.Contains('*')) || (sOne.Contains('/')) || (sOne.Contains('-')) || (sOne.Contains('+')) || (sOne.Contains('%'))){
I should also note that sOne.Contains()
refers to the following code...
public boolean Contains(char key) {
// Checks stack for key
boolean retval = arrs.contains(key);
return retval;
}
It should also be noted that those five chars will never be changed.
You could use a breaking for-each loop over a character array:
for (char c : "*/-+%".toCharArray()) {
if (sOne.Contains(c)) {
// ...
break;
}
}
If you're extremely concerned about performance you might also want to pull out the toCharArray()
call and cache the result in a static final char[]
constant.
You could even use this strategy to define other convenience methods on your sOne
object, like ContainsAny
or ContainsAll
(credit to Sina Madrid for the name ContainsAny
):
public boolean ContainsAny (CharSequence keys) {
for (int i = 0; i < keys.length; i++)
if (Contains(keys.charAt(i)) return true;
return false;
}
public boolean ContainsAll (CharSequence keys) {
for (int i = 0; i < keys.length; i++)
if (!Contains(keys.charAt(i)) return false;
return true;
}
Usage would look something like this:
if (sOne.ContainsAny("*/-+%")) {
// ...
}
You can try using regular expression like this
if (sOne.matches(".*[-*/+%].*")) {
// your code
}
Somewhere, you need the characters in a list:
List<Character> keys = Arrays.asList('*', '/', '-', '+', '%');
And then you can do:
if (keys.stream().anyMatch(sOne::Contains)) {
How about this method: Items are your keys stored in an Array.
public static boolean stringContainsItemFromList(String inputStr, String[] items)
{
for(int i =0; i < items.length; i++)
{
if(inputStr.contains(items[i]))
{
return true;
}
}
return false;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With