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

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 + "\'");
 
    }
 
}

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 + "\'");
 
    }
 
}

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 + "\'");
 
    }
 
}

输出结果:

' ' 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 + "\'");
 
    }
 
}

结果:

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 + "\'");
 
    }
 
}

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 + "\'");
 
    }
 
}

结果:

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!

Statement
This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to elegantly obtain entity class variable names to build database query conditions?How to elegantly obtain entity class variable names to build database query conditions?Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How to use the Redis cache solution to efficiently realize the requirements of product ranking list?How to use the Redis cache solution to efficiently realize the requirements of product ranking list?Apr 19, 2025 pm 11:36 PM

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

How to safely convert Java objects to arrays?How to safely convert Java objects to arrays?Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

How do I convert names to numbers to implement sorting and maintain consistency in groups?How do I convert names to numbers to implement sorting and maintain consistency in groups?Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to set the default run configuration list of SpringBoot projects in Idea for team members to share?How to set the default run configuration list of SpringBoot projects in Idea for team members to share?Apr 19, 2025 pm 11:24 PM

How to set the SpringBoot project default run configuration list in Idea using IntelliJ...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.