Java分割以空格开头的字符串[重复]

时间:2022-08-22 12:50:47

This question already has an answer here:

这个问题在这里已有答案:

I know how to split a string by space as the following:

我知道如何按空格分割字符串如下:

String[] array = string.split(" ");

This works great until I try to split string that starts with a space like

这很有效,直到我尝试拆分以类似空格开头的字符串

" I like apple"

“ 我喜欢苹果”

The result looks something like this:

结果看起来像这样:

{"", "I", "like", "apple"}

{““, “我喜欢苹果”}

How can I split the string so it only keeps strings that is not empty?

如何拆分字符串以便它只保留非空的字符串?

2 个解决方案

#1


2  

You can call string.trim()and then string.split(" "). The trim() method removes spaces before the first non-space-character and after the last non-space-character.

您可以调用string.trim()然后调用string.split(“”)。 trim()方法在第一个非空格字符之前和最后一个非空格字符之后删除空格。

#2


1  

To remove leading and trailing spaces, you can use .trim().

要删除前导和尾随空格,可以使用.trim()。

String[] array = string.trim().split(" ");

#1


2  

You can call string.trim()and then string.split(" "). The trim() method removes spaces before the first non-space-character and after the last non-space-character.

您可以调用string.trim()然后调用string.split(“”)。 trim()方法在第一个非空格字符之前和最后一个非空格字符之后删除空格。

#2


1  

To remove leading and trailing spaces, you can use .trim().

要删除前导和尾随空格,可以使用.trim()。

String[] array = string.trim().split(" ");