如何在 Java 中删除字符串中的空格

本教程介绍了如何在 Java 中从字符串中删除空格,并列举了一些示例代码来了解空格删除过程。

在 Java 中如何删除字符串中的空白处

空格是指在字符串中表示一个空格的字符,它可以是" "\n、\t 等。要从字符串中删除这些字符,有几种方法,例如 replace() 方法,replaceAll()regex 等。让我们看看下面的例子。

在 Java 中使用 replaceAll() 删除空白字符

在这里,我们使用 String 类的 replaceAll() 方法来删除空格。这个方法使用一个 regex 作为参数,并在去除所有空白后返回一个字符串。

public class SimpleTesting {
	public static void main(String[] args) {
		String str = "Programming is easy to learn";
		String result = str.replaceAll("\\s+","");
		System.out.println(result);
	}
}

输出:

Programminiseasytolearn

在 Java 中使用 Apache 库删除 whitespace

如果你使用 Apache 库,那么可以使用 StringUtils 类的 deleteWhitespace() 方法在 Java 中删除字符串中的空白。请看下面的例子和输出。

import org.apache.commons.lang3.StringUtils;
public class SimpleTesting {
	public static void main(String[] args) {
		String str = "Programming is easy to learn";
		String result = StringUtils.deleteWhitespace(str);
		System.out.println(result);
	}
}

输出:

Programminiseasytolearn

在 Java 中使用 Pattern 和 Matcher 删除空白字符

我们可以使用 PatternMatcher 类与 replaceAll() 方法来删除 Java 字符串中的所有空格。

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class SimpleTesting {
	public static void main(String[] args) {
		String str = "Programming is easy to learn";
		Pattern p = Pattern.compile("[\\s]");
        Matcher m = p.matcher(str);
        String result = m.replaceAll("");
		System.out.println(result);
	}
}

输出:

Programminiseasytolearn

在 Java 中删除字符串中的空格

如果你只想从一个字符串中删除空格,那么使用 String 类的 replace() 方法。在 Java 中,它将替换掉字符串中所有的空格(不是所有的空白符号,比如\t,\n 不会被删除。)。

public class SimpleTesting {
	public static void main(String[] args) {
		String str = "Programming is easy to learn";
        String result = str.replace(" ", "");
		System.out.println(result);
	}
}

输出:

Programminiseasytolearn

在 Java 中使用 Apache 删除空格

在这里,我们使用 ApacheStringUtils 类的 replace() 方法来替换 Java 中字符串的所有空格。

import org.apache.commons.lang3.StringUtils;
public class SimpleTesting {
	public static void main(String[] args) {
		String str = "Programming is easy to learn";
        String result = StringUtils.replace(str, " ", "");
		System.out.println(result);
	}
}

输出:

Programminiseasytolearn

如何在 Java 中删除字符串中的最后一个字符

本教程介绍了如何在 Java 中删除字符串中的最后一个字符,还列举了一些示例代码来理解这个主题。删除最后一个字符的方法有好几种,比如 substring() 方法、StringUtils 类等。让我们来仔细看看这些例子。

使用 Java 中的 substring() 方法从字符串中删除最后一个字符

String 类的 substring() 方法用于从字符串对象中获取子字符串。它需要两个参数:起始索引和最后索引。在这里,我们使用 substring() 方法在排除最后一个字符后得到一个字符串。请看下面的例子。

public class SimpleTesting
{
	public static void main(String args[])
	{
		String str = "removea";
		str = str.substring(0, str.length()-1);
		System.out.println(str);
	}
}

输出:

remove

在 Java 中使用 replaceFirst() 方法从字符串中删除最后一个字符

我们可以使用 replaceFirst() 方法从字符串中删除最后一个字符。它在替换了这个字符后返回一个字符串。请看下面的例子。

public class SimpleTesting
{
	public static void main(String args[])
	{
		String str = "removea";
		str = str.replaceFirst(".$","");
		System.out.println(str);
	}
}

输出:

remove

使用 Java 中的 removeEnd() 方法从字符串中删除最后一个字符

如果你正在使用 Apache commons lang 库,最好使用 StringUtils 类,它提供 removeEnd() 方法来删除字符串的最后一个字符。请看下面的例子。

import org.apache.commons.lang3.StringUtils;
public class SimpleTesting
{
	public static void main(String args[])
	{
		String str = "removea";
		str = StringUtils.removeEnd(str, "a");
		System.out.println(str);
	}
}

输出:

remove

使用 Java 中的 chop() 方法从字符串中删除最后一个字符

另一个方法,StringUtils 类的 chop(),从指定的字符串中删除最后一个字符后返回一个字符串。

import org.apache.commons.lang3.StringUtils;
public class SimpleTesting
{
	public static void main(String args[])
	{
		String str = "removea";
		str = StringUtils.chop(str);
		System.out.println(str);
	}
}

输出:

remove

使用 Java 中的 substring() 方法从字符串中删除最后一个字符

StringUtils 类提供了 substring() 方法,该方法需要三个参数。第一个是一个字符串,第二个是一个起始索引,第三个是字符串的结束索引。它返回一个字符串,也就是指定字符串的子字符串。请看下面的例子。

import org.apache.commons.lang3.StringUtils;
public class SimpleTesting
{
	public static void main(String args[])
	{
		String str = "removea";
		str = StringUtils.substring(str, 0, -1);
		System.out.println(str);
	}
}

输出:

remove

在 Java 8 或更高版本中删除字符串中的最后一个字符

如果你使用的是更高版本的 Java,你可以使用 Optional 类来避免 null 异常,并采用函数方法从字符串中删除最后一个字符。

import java.util.Optional;
public class SimpleTesting
{
	public static void main(String args[])
	{
		String str = "removea";
		str = Optional.ofNullable(str)
	      .filter(s -> s.length() != 0)
	      .map(s -> s.substring(0, s.length() - 1))
	      .orElse(str);
		System.out.println(str);
	}
}

输出:

remove

如何在 Java 中删除字符串中的标点符号

本教程介绍了如何在 Java 中删除字符串中的标点符号,还列举了一些示例代码来理解这个话题。

标点符号基本上是一些特殊的字符,用来使文本的语法正确。一些标点符号有逗号(,)、冒号(:)、问号(?)等。让我们看看 Java 中的一些例子。

使用 Java 中的 replaceAll() 方法从字符串中删除标点符号

我们可以在 replaceAll() 方法中使用一个 regex 模式,模式为\p{Punct},来删除字符串中的所有标点符号,得到一个无标点符号的字符串。regex 模式为\p{Punct},表示所有的标点符号。请看下面的例子。

public class SimpleTesting {
	public static void main(String[] args){
		String str = "String - is a squence of chars:~!@#$%^&*(). Test.";
		System.out.println(str);
		String result = str.replaceAll("\\p{Punct}", "");
		System.out.println(result);
	}
}

输出:

String - is a squence of chars:~!@#$%^&*(). Test.
String  is a squence of chars Test

如何在 JavaScript 中删除字符串中的空格

本文将介绍从字符串中删除空格的不同方法,特别是如何删除制表符和换行符。下面的每个方法都会有一个代码示例,你可以在你的机器上运行。

replace() 方法接受一个指定的值或一个正则表达式,并将它们替换到一个给定的字符串中。它返回一个新的字符串,其中指定的值被替换。

使用 replace() 只替换白色空间

string.replace(/ /g, "")

正则表达式包含一个空格字符(" ")和全局属性。它将搜索字符串中的每一个空格,然后用第二个参数中给出的空字符串替换它们。

例子

<!DOCTYPE html>
<html>
<head>
    <title>
       Remove spaces from a string using JavaScript
    </title>
</head>
<body>
    <h2>
        Remove spaces from a string using JavaScript
    </h2>
    <p>
        Original string is:
        site/ delft stack .com/
    </p>
    <p>
        New Sentence is:
        <span class="outputString"></span>
    </p>
    <button onclick="removeSpacesFromString()">
        Clean Spaces
    </button>
    <script type="text/javascript">
        const removeSpacesFromString = () => {
            let text1 =
                "site/ delft stack .com/";
            let text2 =
                text1.replace(/ /g, "");
            document.querySelector('.outputString').textContent
                    = text2;
        }
    </script>
</body>
</html>

输出:

如何在 JavaScript 中删除字符串中的空格

使用 replace() 只替换所有空格

string.replace(/\s+/g, '')

正则表达式模式 s 指的是任何空格符号:空格、制表符和换行符。

例子

<script type="text/javascript">
    const removeSpacesFromString = () => {
        let text1 =
            "site/ delft stack .com/";
        let text2 =
            text1.replace(/\s+/g, '');
        document.querySelector('.outputString').textContent
            = text2;
    }
</script>

在 JavaScript 中使用 split()join() 方法从字符串中删除空格

split() 方法将一个字符串分割成一个数组并返回新的数组。

join() 方法将一个数组中的所有元素连接起来,返回一个新的字符串。

我们将使用 split 方法将字符串分割成一个以空格字符" "作为定界符的数组,然后使用 join 方法将数组转换为一个字符串。它用这两种方法去掉了空白字符。

例子:

<html>
<head>
    <title>
      Remove spaces from a string using JavaScript
    </title>
</head>
<body>
    <h2>
        Remove spaces from a string using JavaScript
    </h2>
    <p>
        Original string is:
        site/ delft stack .com/
    </p>
    <p>
        New Sentence is:
        <span class="outputString"></span>
    </p>
    <button onclick="removeSpacesFromString()">
        Clean Spaces
    </button>
    <script type="text/javascript">
        const removeSpacesFromString = () => {
            let text1 =
                "site/ delft stack .com/";
            let text2 =
                text1.split(" ").join("");
            document.querySelector('.outputString').textContent
                    = text2;
        }
    </script>
</body>
</html>