Java: Splitting a string by whitespace when there is a variable number of whitespaces between words?

前端 未结 8 1197
醉话见心
醉话见心 2021-01-01 03:17

I have the following:

String string = \"1-50  of 500+\";
String[] stringArray = string.split(\" \");

Printing out all the elements in this

8条回答
  •  执念已碎
    2021-01-01 04:05

    With guava Splitter:

    package com.stackoverflow.so19019560;
    
    import com.google.common.base.CharMatcher;
    import com.google.common.base.Splitter;
    import com.google.common.collect.Lists;
    
    import java.util.List;
    
    public class Foo {
    
        private static final Splitter SPLITTER = Splitter.on(CharMatcher.WHITESPACE).omitEmptyStrings();
    
        public static void main(final String[] args) {
            final String string = "1-50  of \t\n500+";
            final List elements = Lists.newArrayList(SPLITTER.split(string));
    
            // output
            for (int i = 0; i < elements.size(); i++) {
                System.out.println(String.format("Element %d: %s", i + 1, elements.get(i)));
            }
        }
    }
    

    Output:

    Element 1: 1-50
    Element 2: of
    Element 3: 500+
    

提交回复
热议问题