示例 1: 删除所有空格的程序
public class Whitespaces { public static void main(String[] args) { String sentence = "T his is b ett er."; System.out.println("Original sentence: " + sentence); sentence = sentence.replaceAll("\\s", ""); System.out.println("After replacement: " + sentence); } }
输出
Original sentence: T his is b ett er.
After replacement: thisisbetter.
在上面的程序中,我们使用String的
replaceAll()
方法来删除和替换字符串
sentence中的所有空格。
要了解更多信息,请访问 Java String replaceAll()。
我们使用了正则表达式
\\s
来查找字符串中的所有空白字符(制表符、空格、换行符等)。然后,我们将其替换为
""
(空字符串文字)。
示例 2: 从用户那里获取字符串并删除空格
import java.util.Scanner; class Main { public static void main(String[] args) { // create an object of Scanner Scanner sc = new Scanner(System.in); System.out.println("Enter the string"); // take the input String input = sc.nextLine(); System.out.println("Original String: " + input); // remove white spaces input = input.replaceAll("\\s", ""); System.out.println("final String: " + input); sc.close(); } }
输出
Enter the string
J av a- P rog ram m ing
Original String: J av a- P rog ram m ing
final String: Java-Programming
在上面的例子中,我们使用了 Java Scanner 来获取用户的输入。
这里,
replaceAll()
方法替换字符串中的所有空格。