欢迎访问宙启技术站
智能推送

使用Java函数删除字符串中的所有空格

发布时间:2023-11-05 02:51:25

要删除字符串中的所有空格,我们可以使用Java中的replaceAll()方法。该方法允许我们使用正则表达式来匹配并替换字符串中的内容。

以下是使用replaceAll()方法删除字符串中所有空格的代码示例:

public class RemoveSpaces {
    public static void main(String[] args) {
        String str = "This is a sample string with spaces.";
        
        // 使用replaceAll()方法删除所有空格
        String newStr = str.replaceAll(" ", "");
        
        System.out.println("原始字符串: " + str);
        System.out.println("删除空格后的字符串: " + newStr);
    }
}

输出结果:

原始字符串: This is a sample string with spaces.
删除空格后的字符串: Thisisasamplestringwithspaces.

在上面的示例中,我们首先定义了一个包含空格的字符串str。然后,我们使用replaceAll()方法,并传入参数" ",该参数是一个正则表达式,用于匹配空格。这里的空格被替换为空字符串。最后,我们将删除所有空格后的新字符串打印输出。

这样,我们就通过使用Java函数成功删除了字符串中的所有空格。