Reputation: 8009
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
Upvotes: 2
Views: 9844
Reputation: 18064
Try this way:
String[] result = "HUNTSVILLE, AL 30 39.8 44.3 52.3".split("[ ]{2,}");
for (int x=0; x<result.length; x++)
System.out.println(result[x]);
[ ] - Represents space
{2,} - Represents more than 2
Upvotes: 3
Reputation: 1975
/*
* Uses split to break up a string of input separated by
* whitespace.
*/
import java.util.regex.*;
public class Splitter {
public static void main(String[] args) throws Exception {
// Create a pattern to match breaks
Pattern p = Pattern.compile("[ ]{2,}");
// Split input with the pattern
String[] result =
p.split("one,two, three four , five");
for (int i=0; i<result.length; i++)
System.out.println(result[i]);
}
}
Upvotes: 2
Reputation: 170158
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
Upvotes: 8
Reputation: 9380
Can't you use split?
String[] tokens = string.split(" ");
You have to filter empty entries though.
Upvotes: 4