Table of Contents
trim()
strip()
stripLeading() 和 stripTrailing()
replace
replaceAll
replaceFirst
Home Java javaTutorial What are the ways to remove spaces from String strings in java?

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

May 17, 2023 pm 11:31 PM
java string

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!

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

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Perfect Number in Java Perfect Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

Weka in Java Weka in Java Aug 30, 2024 pm 04:28 PM

Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

Smith Number in Java Smith Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

TimeStamp to Date in Java TimeStamp to Date in Java Aug 30, 2024 pm 04:28 PM

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

Create the Future: Java Programming for Absolute Beginners Create the Future: Java Programming for Absolute Beginners Oct 13, 2024 pm 01:32 PM

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.

See all articles