Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

tokenizer or split string at multiple spaces in java

I need to tokenize a string where ever there is more than one space.

for instance

"HUNTSVILLE, AL                   30   39.8   44.3   52.3"

becomes

"HUNTSVILLE, AL","30","39.8","44.3","52.3"


StringTokenizer st = new StringTokenizer(str, "   ");

just tokenizes any whitespace, and I can't figure out a regex to do what I need.

Thanks

like image 592
jeremyjjbrown Avatar asked Mar 02 '26 10:03

jeremyjjbrown


2 Answers

Try this:

String s = "HUNTSVILLE, AL                   30   39.8   44.3   52.3";
String[] parts = s.split("\\s{3,}");
for(String p : parts) {
  System.out.println(p);
}

The \s matches any white space char, and {3,} will match it 3 or more times.

The snippet above would print:

HUNTSVILLE, AL
30
39.8
44.3
52.3
like image 134
Bart Kiers Avatar answered Mar 05 '26 00:03

Bart Kiers


Can't you use split?

String[] tokens = string.split("  ");

You have to filter empty entries though.

like image 20
MasterCassim Avatar answered Mar 04 '26 22:03

MasterCassim



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!