2

Sorry if this question has already been asked, but I could only find results of c#. So I have this StringBuilder:

 StringBuilder sb = new StringBuilder(" 111     11 ");

and I want to split it into an array using this method:

String[] ar = sb.toString().split(" ");

As expected the result array has some empty entries. My question is if I can remove these empty spaces directly when I split the StringBuilder or I have to do it afterwards.

Petar Yakov
  • 169
  • 2
  • 14

5 Answers5

8

split takes a regex. So:

String[] ar = sb.toString().split("\\s+");

The string \\s is regexp-ese for 'any whitespace', and the + is: 1 or more of it. If you want to split on spaces only (and not on newlines, tabs, etc), try: String[] ar = sb.toString().split(" +"); which is literally: "split on one or more spaces".

This trick works for just about any separator. For example, split on commas? Try: .split("\\s*,\\s*"), which is: 0 or more whitespace, a comma, followed by 0 or more whitespace (and regexes take as much as they can).

Note that this trick does NOT get rid of leading and trailing whitespace. But to do that, use trim. Putting it all together:

String[] ar = sb.toString().trim().split("\\s+");

and for commas:

String[] ar = sb.toString().trim().split("\\s*,\\s*");
rzwitserloot
  • 85,357
  • 5
  • 51
  • 72
2

I would use guava for this:

    String t = " 111     11 ";
    Splitter.on(Pattern.compile("\\s+"))
            .omitEmptyStrings()
            .split(t)
            .forEach(System.out::println);
Eugene
  • 117,005
  • 15
  • 201
  • 306
  • Can I store the splitted String in an array using this method? – Petar Yakov Jan 16 '19 at 09:54
  • @PetarYakov you can to a `List`: `Splitter.on(Pattern.compile("\\s+")) .omitEmptyStrings() .splitToList(t);` from here to an array is trivial... – Eugene Jan 16 '19 at 09:58
2

If you do not want to depend on any third party dependencies and do not want to regex filtering,

You can do it in one line with Java 8 Streams API:

Arrays.stream(sb.toString().trim().split(" ")).filter(s-> !s.equals("")).map(s -> s.trim()).toArray();

For a detailed multiline version of the previous:

Arrays.stream(sb.toString()
    .trim() // Trim the starting and ending whitespaces from string
    .split(" ")) // Split the regarding to spaces
    .filter(s-> !s.equals("")) // Filter the non-empty elements from the stream
    .map(s -> s.trim()) // Trim the starting and ending whitespaces from element
    .toArray(); // Collect the elements to object array

Here is the working code for demonstration:

StringBuilder sb = new StringBuilder(" 111     11 ");
Object[] array = Arrays.stream(sb.toString().trim().split(" ")).filter(s-> !s.equals("")).map(s -> s.trim()).toArray();

System.out.println("(" + array[0] + ")");
System.out.println("(" + array[1] + ")");
Akiner Alkan
  • 6,145
  • 3
  • 32
  • 68
1

There is couple of regex to deal with it, i would also prefer @rzwitserloot method, but if you would like to see more.

Check it here : How do I split a string with any whitespace chars as delimiters?

glenatron has explained it :

In most regex dialects there are a set of convenient character summaries you can use for this kind of thing - these are good ones to remember:

\w - Matches any word character.

\W - Matches any nonword character.

\s - Matches any white-space character.

\S - Matches anything but white-space characters.

\d - Matches any digit.

\D - Matches anything except digits.

A search for "Regex Cheatsheets" should reward you with a whole lot of useful summaries.

Thanks to glenatron

Wael Azar
  • 281
  • 1
  • 5
  • 10
0

You can use turnkey solution from Apache Commons. Here is an example:

StringBuilder sb = new StringBuilder(" 111     11 ");
String trimmedString = StringUtils.normalizeSpace(sb.toString());
String[] trimmedAr = trimmedString.split(" ");
System.out.println(Arrays.toString(trimmedAr));

Output: [111, 11].

bovae
  • 312
  • 3
  • 12