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

后端 未结 4 819
青春惊慌失措
青春惊慌失措 2021-01-12 14:43

Quick example:

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


        
4条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-12 15:12

    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.

提交回复
热议问题