If you split a String on a delimiter that doesn't exist then you will get back the original String:
public static void main(String[] args) throws SQLException {
System.out.println(Arrays.toString("My string without pipes".split("\\|")));
}
Output:
[My string without pipes]
If you try and split on a character that the string ends with you do not get an empty String in the Array:
public static void main(String[] args) throws SQLException {
System.out.println(Arrays.toString("My string ending in pipe|".split("\\|")));
}
Output:
[My string ending in pipe]
All that happens is the delimiter at the end is dropped.
So your logic is wrong. The reason you got the correct answer in your second check is not because the check is correct but because the pipe happened to be at the end.
Generally, you will not get the number of delimiters in a String using spilt, you will get the number +1 unless your String starts or ends with the delimiter - in which case it will simply be dropped.
What you need to do is use regex to search for all pipes not preceded by a closing parenthesis. You can do this with negative lookbehind:
public static void main(String[] args) throws SQLException {
final String s1 = "(A#,A#,A#),(B#,B#,C#),(B#,B#,C#),(Bb,Bb,Cb)|(Ab,Ab,Ab),(Bb,Bb,Cb),(Bb,Bb,Cb),(Bb,Bb,Cb)|";
final String s2 = "(A#,A#,A#),(B#,B#,C#),(B#,B#,C#),(Bb,Bb,Cb)|A#,B#,C#,D#, E#,F#,G#, | ,A, , , , , , , , , , , , , , |";
final Pattern pattern = Pattern.compile("(?<!\\))\\|");
int count = 0;
final Matcher matcher = pattern.matcher(s1);
while (matcher.find()) {
++count;
}
System.out.println(count);
count = 0;
matcher.reset(s2);
while (matcher.find()) {
++count;
}
System.out.println(count);
}
Output:
0
2
line2.split("[\\|]");escaping here is redundant as the meta character is already in character class.line2.split("[|]");is fine . :)Stringback in a one elementArray. More generally if you split aStringwith one delimiter in it you get back anArraysize 2, one with two delimiters will give back anArraysize 3. See a pattern here?