Java如何清除空格?

在Java编程中,如何清除/删除空格?

以下示例演示如何使用Util.regex.Pattern类的matcher.replaceAll(stringname)方法来删除空格。

package com.yiibai;

import java.util.regex.Matcher; import java.util.regex.Pattern; public class RemovingWhitespaces { public static void main(String[] argv) { String str = "This is a Java program. This is another Java Program."; String pattern = "[\\s]"; String replace = ""; Pattern p = Pattern.compile(pattern); Matcher m = p.matcher(str); str = m.replaceAll(replace); System.out.println("After Whitespaces trim: "+str); } } 
Java

上述代码示例将产生以下结果 -

After Whitespaces trim: ThisisaJavaprogram.ThisisanotherJavaProgram.
Shell

示例-2

以下是删除空格的另一个示例。

package com.yiibai;

import java.util.Scanner ; import java.lang.String ; public class RemovingWhitespaces2 { public static void main (String[]args) { String s1 = null; Scanner scan = new Scanner(System.in); System.out.println("Enter a new string: "); s1 = scan.nextLine(); System.out.println("Input String is : "+s1); String s2 = s1.replaceAll("\\s+",""); System.out.println("Output String is : "+s2); } } 
Java

上述代码示例将产生以下结果 -

Enter a new string: 
this is a new string with whitespace.
Input String is  : this is a new string with whitespace.
Output String is  : thisisanewstringwithwhitespace.

转载于:https://www.cnblogs.com/borter/p/9617148.html

你可能感兴趣的:(Java如何清除空格?)