标签:yii The rgs 示例 removing keyword 空格 pack lin
在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.
标签:yii The rgs 示例 removing keyword 空格 pack lin
原文地址:https://www.cnblogs.com/borter/p/9617148.html