Reputation: 6274
I have this code that filters a String str
, keeping only some chars
, resulting in the reduced String fStr
. The subtlety is that I only keep a target char
, if it is not equal to the last char
in fStr
:
ArrayList<Character> targetChars = //{a, b, c};
String str = "axxbxxxxbxbxcxa", fStr = "";
for(int i = 0, s = 0 ; i < str.length() ; i++) {
char c = str.charAt(i);
if(targetChars.contains(c)) {
if(s > 0 && fStr.charAt(s-1) != c) {
fStr += c;
s++;
}
}
}
fStr → "abca"
In the innermost if
statement, I have to include s > 0
before fStr.charAt(s-1) != c
, otherwise the latter will throw an OutOfBounds
exception the first time targetChars.contains(c)
is true
. But only the first time, it annoys me that the loop will always check that I won't be out of bounds, given that it only has to do it once. I know I could do something like that:
ArrayList<Character> targetChars = //{a, b, c};
String str = "auebskrubnbocpa", fStr = "";
int i = 0, s = 0;
for(; i < str.length() ; i++) {
char c = str.charAt(i);
if(targetChars.contains(c)) {
fStr += c;
s++;
i++;
break;
}
}
for(; i < str.length() ; i++) {
char c = str.charAt(i);
if(targetChars.contains(c)) {
if(fStr.charAt(s-1) != c) {
fStr += c;
s++;
}
}
}
But is there a more elegant and less annoying way to dynamically truncate a conditional statement?
Upvotes: 0
Views: 2623
Reputation: 1506
Here is how I would do it, but not sure if it suits your needs
public class Example {
public static void main(String[] args) {
char[] targetChars = {'a', 'b', 'c'};
String str = "axxbxxxxbxbxcxa", fStr = " ";
for(int i = 0 ; i < str.length() ; i++) {
char c = str.charAt(i);
if(isAcceptableChar(c, targetChars)) {
if(fStr.charAt(fStr.length() - 1) != c) {
fStr = fStr.trim() + c;
}
}
}
System.out.println(fStr);
}
private static boolean isAcceptableChar(char newChar, char[] targetChars) {
boolean value = false;
for(char ch : targetChars){
if(ch == newChar) {
value = true;
break;
}
}
return value;
}
}
Upvotes: 1
Reputation: 115
Sure there is, just call a function that returns a boolean value that you use in your if condition. Different functions could be called at different times by using a function pointer.
Upvotes: 0
Reputation: 718946
Is there a way to dynamically change conditions in if statement in Java?
No there isn't. The original version of your code is the best from a readability perspective.
However, if you are concerned about efficiency, then you should be using a StringBuilder
rather than fStr += c
.
Also a char[]
and an explicit for
loop is likely to be faster than ArrayList<Character>.contains
.
Upvotes: 2