JAVA 多个空格分割字符串

基本能够想到的方法:str.split(" ")
实际上这个用法在处理单个空格分隔单词的字符串上是有效的:

String sentence = "I am a loser";
String[] words = sentence.split(" ");
System.out.println(Arrays.toString(words)); // [I, am, a, loser]

如果是有多个空格分隔单词的字符串就会出现问题:

String sentence = "I am   a    loser";
String[] words = sentence.split(" ");
System.out.println(Arrays.toString(words)); // [I, am, , , a, , , , loser]

此时要使用正则规避这个问题:

String sentence = "I am   a    loser";
String[] words = sentence.split("\\s+");
System.out.println(Arrays.toString(words)); // [I, am, a, loser]

但这种方法依旧无法消除前导空格:

String sentence = "    I am   a    loser";
String[] words = sentence.split("\\s+");
System.out.println(Arrays.toString(words)); // [, I, am, a, loser]

所以调用split前可以先调用trim消除前导空格:

String sentence = "    I am   a    loser";
String[] words = sentence.trim().split("\\s+");
System.out.println(Arrays.toString(words)); // [I, am, a, loser]

你可能感兴趣的:(Java,小技巧,java,开发语言)