可以使用正则表达式的replaceAll方法删除 String 中的额外空格。
example = example.replaceAll(" +", " ");
这个例子首先创建要清理的字符串,字符串具有由未知数量的空格分隔的字符。 表达式尽可能多地匹配空格,并用一个空格替换它们。 输出然后写入System.out。
public class RemoveConsecutiveSpace {
public static void main(String[] argv){
String example = "A B C D E";
example = example.replaceAll(" +", " ");
System.out.print( "Cleaned String: " + example);
}
}
Cleaned String: A B C D E