Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split a string with whitespace chars at the beginning?

Quick example:

public class Test {
    public static void main(String[] args) {
        String str = "   a b";
        String[] arr = str.split("\\s+");
        for (String s : arr)
            System.out.println(s);
    }
}

I want the array arr to contain 2 elements: "a" and "b", but in the result there are 3 elements: "" (empty string), "a" and "b". What should I do to get it right?

like image 747
Radek Wyroslak Avatar asked Oct 31 '11 23:10

Radek Wyroslak


People also ask

How do you split a string on the first occurrence of certain characters?

Using the split() Method For example, if we put the limit as n (n >0), it means that the pattern will be applied at most n-1 times. Here, we'll be using space (” “) as a regular expression to split the String on the first occurrence of space.

How do I split a string into whitespace characters?

To split a string with space as delimiter in Java, call split() method on the string object, with space " " passed as argument to the split() method. The method returns a String Array with the splits as elements in the array.

How do you cut a space in front of a string?

You can call the trim() method on your string to remove whitespace from the beginning and end of it. It returns a new string. var hello = ' Hello there! '; // returns "Hello there!" hello.

How do you split the first three characters of a string?

Use the string. slice() method to get the first three characters of a string, e.g. const first3 = str. slice(0, 3); . The slice method will return a new string containing the first three characters of the original string.


3 Answers

Kind of a cheat, but replace:

String str = "   a b";

with

String[] arr = "   a b".trim().split("\\s+");
like image 137
Joe Avatar answered Oct 20 '22 19:10

Joe


The other way to trim it is to use look ahead and look behind to be sure that the whitespace is sandwiched between two non-white-space characters,... something like:

String[] arr = str.split("(?<=\\S)\\s+(?=\\S)");

The problem with this is that it doesn't trim the leading spaces, giving this result:

   a
b

but nor should it as String#split(...) is for splitting, not trimming.

like image 36
Hovercraft Full Of Eels Avatar answered Oct 20 '22 21:10

Hovercraft Full Of Eels


The simple solution is to use trim() to remove leading (and trailing) whitespace before the split(...) call.

You can't do this with just split(...). The split regex is matching string separators; i.e. there will necessarily be a substring (possibly empty) before and after each matched separator.

You can deal with the case where the whitespace is at the end by using split(..., 0). This discards any trailing empty strings. However, there is no equivalent form of split for discarding leading empty strings.

like image 23
Stephen C Avatar answered Oct 20 '22 21:10

Stephen C