首页 > 解决方案 > why does java's String split("\\s") have an empty string in the array?

问题描述

Given the sentence "The brown fox jumped the fence jumped. The jumped fox? The fox. Jumped" splitting by whitespace shows an empty string in the array. I expected words or words with punctuation. Where did this empty string come from in the sentence?

标签: javastring

解决方案


这是因为您的字符串包含连续的空白字符,例如

jumped.  The
       ^^

这两个空格之间有一个长度为零的字符串,所以如果你拆分每个空格字符,你会得到它们之间的空字符串。

如果您想将它们匹配为单个分隔符,请使用量词,例如

"\\s+"

推荐阅读