Java删除空格
如何去除空格?
解决方法
下面的示例演示如何使用Util.regex.Pattern类的matcher.replaceAll(stringname) 方法删除空格。
import java.util.regex.Matcher; import java.util.regex.Pattern; public class Main { public static void main(String[] argv) throws Exception { String ExString = "This is a Java program. This is another Java Program."; String result=removeDuplicateWhitespace(ExString); System.out.println(result); } public static CharSequence removeDuplicateWhitespace(CharSequence inputStr) { String patternStr = "\s+"; String replaceStr = " "; Pattern pattern = Pattern.compile(patternStr); Matcher matcher = pattern.matcher(inputStr); return matcher.replaceAll(replaceStr); } }
结果
上面的代码示例将产生以下结果。
ThisisaJavaprogram.ThisisanotherJavaprogram.