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.