Java教程

Java删除字符串中的所有空格

在此程序中,我们的任务是删除字符串中的所有空格。为此,我们需要遍历字符串,并检查字符串的任何字符是否与空格字符匹配。如果是这样,请使用任何内置方法(例如replace())为空。
在C中,我们没有任何内置方法可以替换。因此,我们需要运行for循环来遍历字符串,看看是否存在任何空格字符。如果是这样,则从第i个字符开始到len的内部循环(j),并继续用其下一个相邻元素替换每个元素。在此循环结束时,将字符串的长度减少1。重复此过程,直到删除字符串的所有空白为止。
下面给出了程序的算法。

算法

步骤1: START 第2步: DEFINE字符串str1 ="Remove white spaces"。 步骤3: 使用replaceAll() 将所有空格字符替换为空白。 步骤4: 打印str1。 步骤5: END

程序:

public class removeWhiteSpace {
    public static void main(String[] args) {
        String str1="Remove white spaces";
        //Removes the white spaces using regex
        str1 = str1.replaceAll("\\s+", "");
        System.out.println("String after removing all the white spaces : " + str1);
    }
}
输出:
String after removing all the white spaces: Removewhitespaces
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4