I\'m trying to use
\"value1:value2::value3\".split(\":\");
Problem is that I want it to include the blank results.
It returns:
public static void main(String[] args){
String[] arr = "value1:value2::value3".split(":");
for(String elm:arr){
System.out.println("'"+elm+"',");
}
System.out.println(arr.length);
}
prints
'value1',
'value2',
'',
'value3',
4
Which is exactly what you want. Your mistake is somewhere else...
split
does include empty matches in the result, have a look at the docs here. However, by default, trailing empty strings (those at the end of the array) are discarded. If you want to include these as well, try split(":", -1)
.
I think that a StringTokenizer
might work better for you, YMMV.
That should work but give StringTokenizer
a go if you're still having issues.
Use a negative limit in your split statement:
String str = "val1:val2::val3";
String[] st = str.split(":", -1);
for (int i = 0; i< st.length; i++)
System.out.println(st[i]);
Results:
val1
val2
val3
Works for me.
class t {
public static void main(String[] _) {
String t1 = "value1:value2::value3";
String[] t2 = t1.split(":");
System.out.println("t2 has "+t2.length+" elements");
for (String tt : t2) System.out.println("\""+tt+"\"");
}
}
gives the output
$ java t
t2 has 4 elements
"value1"
"value2"
""
"value3"