Home > Java > javaTutorial > body text

What are the ways to remove spaces from String strings in java?

WBOY
Release: 2023-05-17 23:31:55
forward
964 people have browsed it

There are many different ways to remove spaces from strings in Java, such as trim, replaceAll, etc. However, some new features have been added in JDK 11, such as strip, stripLeading, stripTrailing, etc.

How many methods are there to remove spaces from String? The following introduces the native methods of JDK, excluding similar methods in third-party tool libraries

  • trim() : Remove spaces at the beginning and end of the string.

  • strip() : Remove spaces at the beginning and end of the string.

  • stripLeading() : Only remove spaces at the beginning of the string

  • stripTrailing() : Remove only the spaces at the end of the string

  • replace() : Replace all target characters with new characters

  • replaceAll() : Replace all matching characters with new characters. This method takes as input a regular expression to identify the target substring that needs to be replaced

  • replaceFirst() : Replace only the first time of the target substring Occurring characters are replaced with new string

The most important thing to note is that in Java String object is immutable which means we cannot modify the string so All the above methods give us a new string.

trim()

trim() is the most commonly used method by Java developers to remove spaces at the beginning and end of a string

public class StringTest {
 
    public static void main(String[] args) {
 
        String stringWithSpace = "   Hello word java  ";
 
        StringTest.trimTest(stringWithSpace);
 
    }
 
    private static void trimTest(String stringWithSpace){
 
        System.out.println("Before trim : \'" + stringWithSpace + "\'");
 
        String stringAfterTrim = stringWithSpace.trim();
 
        System.out.println("After trim : \'" + stringAfterTrim + "\'");
 
    }
 
}
Copy after login

Output results

Before trim : ' Hello word java '
After trim : 'Hello word java'

By using the trim method, the beginning and end of the original string The spaces have been removed. In fact, the whitespace characters removed by trim refer to any character with an ASCII value less than or equal to 32 (’ U 0020 '):

What are the ways to remove spaces from String strings in java?

strip()

In the release of JDK 11, a new strip() method was added to remove leading and trailing spaces from strings. The

trim method can only remove characters whose ASCII value is less than or equal to 32, but according to the Unicode standard, in addition to characters in ASCII, there are still many other whitespace characters.

And in order to recognize these space characters, starting from Java 1.5, a new isWhitespace(int) method has been added to the Character class. This method uses unicode to identify space characters.

What are the ways to remove spaces from String strings in java?

The strip method newly added in Java 11 uses the Character.isWhitespace(int) method to determine whether they are whitespace characters and delete them:

What are the ways to remove spaces from String strings in java?

What are the ways to remove spaces from String strings in java?

strip example

public class StringTest {
 
    public static void main(String args[]) {
 
      String stringWithSpace ='\u2001' + "  Hello word java  " + '\u2001';
 
        System.out.println("'" + '\u2001' + "' is space : " +  Character.isWhitespace('\u2001'));
 
        StringTest.stripTest(stringWithSpace);
 
    }
 
    private static void stripTest(String stringWithSpace){
 
        System.out.println("Before strip : \'" + stringWithSpace + "\'");
 
        String stringAfterTrim = stringWithSpace.strip();
 
        System.out.println("After strip : \'" + stringAfterTrim + "\'");
 
    }
 
}
Copy after login

result

' is space : true
Before strip : 'Hello word java '
After strip : 'Hello word java'

strip() method in Java 11 is faster than trim()# The ## method is more powerful. It can remove many whitespace characters that are not in ASCII. The way to judge is through the Character.isWhitespace() method.

The difference between trim() and strip() methods

trimstripJava 1 IntroducedJava 11 IntroducedUse ASCIIUse Unicode valuesRemove the beginning and trailing whitespace charactersDelete leading and trailing whitespace charactersDelete characters whose ASCII value is less than or equal to ’U 0020’ or ’32’Remove all whitespace characters according to unicode

stripLeading() 和 stripTrailing()

stripLeading()stripTrailing()方法也都是在Java 11中添加的。作用分别是删除字符串的开头的空格以及删除字符串的末尾的空格。
stripLeadingstripTrailing也使用Character.isWhitespace(int)来标识空白字符。用法也和strip类似:

public class StringTest {
 
    public static void main(String args[]) {
 
      String stringWithSpace ='\u2001' + "  Hello word java  " + '\u2001';
 
        System.out.println("'" + '\u2001' + "' is space : " +  Character.isWhitespace('\u2001'));
 
        StringTest.stripLeadingTest(stringWithSpace);
 
        StringTest.stripTrailingTest(stringWithSpace);
 
    }
 
 
    private static void stripLeadingTest(String stringWithSpace){
        System.out.println("删除开头的空白字符");
 
        System.out.println("Before stripLeading : \'" + stringWithSpace + "\'");
 
        String stringAfterTrim = stringWithSpace.stripLeading();
 
        System.out.println("After stripLeading : \'" + stringAfterTrim + "\'");
 
    }
 
 
     private static void stripTrailingTest(String stringWithSpace){
         System.out.println("删除结尾的空白字符");
 
        System.out.println("Before stripTrailing : \'" + stringWithSpace + "\'");
 
        String stringAfterTrim = stringWithSpace.stripTrailing();
 
        System.out.println("After stripTrailing : \'" + stringAfterTrim + "\'");
 
    }
 
}
Copy after login

输出结果:

' ' is space : true
删除开头的空白字符
Before stripLeading : '  Hello word java  '
After stripLeading : 'Hello word java  '
删除结尾的空白字符
Before stripTrailing : '  Hello word java  '
After stripTrailing : '  Hello word java'

replace

replace是从java 1.5中添加的,可以用指定的字符串替换每个目标子字符串。

此方法替换所有匹配的目标元素

 public class StringTest {
 
    public static void main(String args[]) {
 
        String stringWithSpace ="  Hello word java  ";
 
        StringTest.replaceTest(stringWithSpace);
 
    }
 
 
 
    private static void replaceTest(String stringWithSpace){
 
        System.out.println("Before replace : \'" + stringWithSpace + "\'");
 
        String stringAfterTrim = stringWithSpace.replace(" ", "");
 
        System.out.println("After replace : \'" + stringAfterTrim + "\'");
 
    }
 
}
Copy after login

结果:

Before replace : ' Hello word java '
After replace : 'Hellowordjava'

使用replace方法可以替换掉字符串中的所有空白字符。需要特别注意的是,和trim方法一样,replace方法只能替换ASCII中的空白字符。

replaceAll

replaceAll是Jdk 1.4中添加的最强大的字符串操作方法之一。我们可以将这种方法用于许多目的。
使用replaceAll()方法,我们可以使用正则表达式来用来识别需要被替换的目标字符内容。使用正则表达式,就可以实现很多功能,如删除所有空格,删除开头空格,删除结尾空格等等。

\s+ 所有的空白字符
^\s+ 字符串开头的所有空白字符
\s+$ 字符串结尾的所有空白字符

在java中要添加\我们必须使用转义字符,所以对于\s+ 我们必须使用 \\s+

replaceAll(regex, “”); // 将正则表达式匹配到的内容,替换为""

public class StringTest {
 
    public static void main(String args[]) {
 
        String stringWithSpace ="  Hello word java  ";
 
        StringTest.replaceAllTest(stringWithSpace," ");
 
        StringTest.replaceAllTest(stringWithSpace,"\\s+");
 
        StringTest.replaceAllTest(stringWithSpace,"^\\s+");
 
        StringTest.replaceAllTest(stringWithSpace,"\\s+$");
 
    }
 
 
    private static void replaceAllTest(String stringWithSpace,String regex){
 
        System.out.println("Before replaceAll with '"+ regex +"': \'" + stringWithSpace + "\'");
 
        String stringAfterTrim = stringWithSpace.replaceAll(regex, "");
 
        System.out.println("After replaceAll with '"+ regex +"': \'" + stringAfterTrim + "\'");
 
    }
 
}
Copy after login

Before replaceAll with ' ': ' Hello word java '
After replaceAll with ' ': 'Hellowordjava'
Before replaceAll with '\s+': ' Hello word java '
After replaceAll with '\s+': 'Hellowordjava'
Before replaceAll with '^\s+': ' Hello word java '
After replaceAll with '^\s+': 'Hello word java '
Before replaceAll with '\s+$': ' Hello word java '
After replaceAll with '\s+$': ' Hello word java'

replaceFirst

replaceFirst方法也是在jdk1.4中添加的,它只将给定正则表达式的第一个匹配项替换为替换字符串。

public class StringTest {
 
    public static void main(String args[]) {
 
        String stringWithSpace ="  Hello word java  ";
 
        StringTest.replaceFirstTest(stringWithSpace," ");
 
        StringTest.replaceFirstTest(stringWithSpace,"\\s+");
 
        StringTest.replaceFirstTest(stringWithSpace,"^\\s+");
 
        StringTest.replaceFirstTest(stringWithSpace,"\\s+$");
 
    }
 
 
    private static void replaceFirstTest(String stringWithSpace,String regex){
 
        System.out.println("Before replaceFirst with '"+ regex +"': \'" + stringWithSpace + "\'");
 
        String stringAfterTrim = stringWithSpace.replaceFirst(regex, "");
 
        System.out.println("After replaceFirst with '"+ regex +"': \'" + stringAfterTrim + "\'");
 
    }
 
}
Copy after login

结果:

Before replaceFirst with ' ': '  Hello word java  '
After replaceFirst with ' ': ' Hello word java  '
Before replaceFirst with '\s+': '  Hello word java  '
After replaceFirst with '\s+': 'Hello word java  '
Before replaceFirst with '^\s+': '  Hello word java  '
After replaceFirst with '^\s+': 'Hello word java  '
Before replaceFirst with '\s+$': '  Hello word java  '
After replaceFirst with '\s+$': '  Hello word java'

The above is the detailed content of What are the ways to remove spaces from String strings in java?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!