问题

首先我们先假设需要对一个字符串"hello world!"做分割,去除中间的空格,获取每一个单词的字符串数组words。

方法1

我们最简单也是最容易的方法是使用split对字符串进行分割。

方法如下:

String s = "hello world!";
String[] words = s.split(" ");
for(String word:words){
    System.out.println(word);
}

打印结果如下:

hello
world!

但是这样的方法在面对多个空格时将会获取空的字符串。例如

String s = "hello  world!";
String[] words = s.split(" ");
for(String word:words){
    System.out.println(word);
}

打印结果如下:

hello

world!

显然这种方式不合我们的预期,接下来我们考虑使用功能更强大一些的正则表达式来达成我们的目标。

方法二

正则表达式\\s+表示匹配任何空白字符一次或多次。我们使用一个更长一点的字符串进行测试:

String str = "hello  world! this  is   right!";
String[] words = str.split("\\s+");
for(String word:words){
    System.out.println(word);
}

打印结果如下:

hello
world!
this
is
right!

可以看到,目前使用正则表达式进行字符串的切分达到了我们的目的。我们再来考虑一种情况,在这个字符串的开头或者结尾处也同样含有空格的情况。例如:

String str = "  hello  world! this  is   right!  ";
String[] words = str.split("\\s+");
for(String word:words){
    System.out.println(word);
}
System.out.println("-------this is endLine-------");

打印结果如下:

hello
world!
this
is
right!
-------this is endLine-------

可以看到,开头的空格并没有被正确切分出来,使用正则表达式也没有达到我们的目的。

方法3

其实,从方法2来看,我们已经很接近了,只是开头这空格有些令人恼怒。也许聪明的你已经在想,假如我能在进行分割之前把字符串的开头空格给处理掉,这样再使用split分割不就好了?Java的String方法中确实有这样一个方法能够办到这件事,看来你和Java语言的设计者所见略同。前面提到的方法叫trim,知道这件事后,接下来就好办了。

我们来测试一下:

String str = "   hello  world! this  is   right!   ";
String afterTrim = str.trim();
System.out.println("after trim:"+afterTrim);
String[] words = afterTrim.split("\\s+");
for(String word:words){
    System.out.println(word);
}
System.out.println("-------this is endLine-------");

打印结果如下:

after trim: hello  world! this  is   right!
hello
world!
this
is
right!
-------this is endLine-------

使用trim,split,正则表达式后,我们完成了对一个字符串去除了空格并提取分隔的单词信息。

获取不含空格字符串

这里简单介绍一下,主要的思路是使用String对象提供的replaceAll方法,这里只给出一种简单实现。

String str = "   hello  world! this  is   right!   ";
System.out.println(str.replaceAll(" +",""));

打印结果如下:

helloworld!thisisright!

上述方法可以去除字符串中的所有空格,包括开头结尾,并返回一个String。

总结

在对一个简单字符串"hello world!"的切分中,我们首先使用了方法1,简单的使用split进行切分,但这种方式无法处理含多个空格间隔的单词切分;这时我们开始求助于方法二,也就是使用正则表达式进行切分,虽然效果很好,但是在这种方法在面对字符串开头含空格的情况下无法正确切割掉开头的空格;最后,我们使用方法3,也就是用trim先对字符串做预处理,消除开头结尾的空格之后再做切分,这样,我们完美完成了我们的任务。

最后文章稍微提了一下对于获取不含空格的字符串的方法。