I have a string like abc~def~ghij~klm~nop~qrstu~vwx~hj
. I want to split it only two times (to three parts as the result): that means wherever I get ~
symbol I need to split abc
, def
and third as a single string only ghij~klm~nop~qrstu~vwx~hj
.
I know how to split into strings wherever ~
symbol comes
String[] parts = stat.split("~");
String part1 = parts[0];
String part2 = parts[1];
String part3 = parts[2];
Here I get only part3 as ghij
, I need the whole string remaining long with ~
symbol.
You can use String.split(String regex, int limit)
.
String[] parts = stat.split("~", 3);
This splits the stat
String only two times, i.e. it splits it in 3 parts:
String[] parts = stat.split("~", 3);
String.split(String regex, int limit)
method allows for control over the number of resulting parts.
Quoting the Javadoc:
The limit parameter controls the number of times the pattern is applied and therefore affects the length of the resulting array. If the limit n is greater than zero then the pattern will be applied at most n - 1 times, the array's length will be no greater than n, and the array's last entry will contain all input beyond the last matched delimiter.
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