简体   繁体   中英

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

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

Can't you use split?

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

You have to filter empty entries though.

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

 /*
 * 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]);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM