String string = "3 5 3 -4 2 3 ";
I want to use split()
here but I need to a separator to be -4
. I don't know which numbers are negative and I need to use split to group positive numbers in separate arrays.
Is it possible?
Edit:
I want to use:
String[] parts = string.split(????);
and receive
parts[0] = "3 5 3"
parts[1] = "2 3"
From what I mentioned in comments, you can use -\\d+
for splitting.
It finds all the places where there is -
followed by any number of digits. We can trim the array elements later if we want
Java Code
String Str = new String("3 5 3 -4 2 3");
String[] x = Str.split("-\\d+");
for (String retval: x){
System.out.println(retval.trim());
}
Ideone Demo
You can use the replace
method to search for a given string (in this case, -4) and replace it with a delimiter of your choice, perhaps a pipe-bar line (|
). Then you can use the split method and use the delimiter that's now inserted to split your array.
string = string.replace(replaceString, "|");
string[] parts = string.split('|');
Admittedly this is a little roundabout, but it's quick, easy, and will work.
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