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

前端 未结 8 1137
醉话见心
醉话见心 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:02
    import java.util.*;
    import java.lang.*;
    import java.io.*;
    
    /* Name of the class has to be "Main" only if the class is public. */
    class Ideone
    {
    public static void main (String[] args) throws java.lang.Exception
    {
        String string = "1-50  of 500+";
        String[] stringArray = string.split("\\s+");
        for (String str : stringArray)
          {
            System.out.println(str);
          }
       }
    }
    
    0 讨论(0)
  • 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<String> 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+
    
    0 讨论(0)
提交回复
热议问题