Java如何清除空格?

2019-10-16 22:25:30

在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);
    }
}

上述程式碼範例將產生以下結果 -

After Whitespaces trim: ThisisaJavaprogram.ThisisanotherJavaProgram.

範例-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);
   }
}

上述程式碼範例將產生以下結果 -

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.