May 31, 2021 Article blog
1. Different ways to remove spaces from a string in java
2. The difference between the trim and strip methods
This article was reproduced from the public number: Hollis
Strings are one of the most commonly used data types in Java. W e often use strings to do a lot of things in our daily development. Such as string stitching, truncation, replacement, etc.
In this article, we describe one of the more common and easy-to-ignore operations to remove spaces from strings.
In fact, there are many different ways to remove spaces from strings in
Java,
such as
trim
replaceAll
and so on.
However, some new features have been added to Java 11, such as
strip
stripLeading
stripTrailing
and so on.
Most of the time, we just use
trim
method to remove extra spaces.
But as if a lot of people hadn't thought about it, is there a better way?
Of course,
trim()
works well in most cases, but there are many different approaches in
Java.
E
ach has its own advantages and disadvantages.
How do we decide which method is best for us?
Next we'll look at a few methods and compare their differences and strengths and weaknesses.
First, let's look at how many methods to remove the space section from
String
and the author summarizes the following 7 (JDK native comes with a method that does not include similar methods in the third-party tool class library):
The most important thing to note is that
String
objects are immutable in
Java,
which means we can't modify strings, so all of the above methods we get is a new string.
Next, we learn the usage for each of these methods and understand its characteristics.
PS: This article code is done using the online run tool (www.jdoodle.com/online-java-compiler/) because my tester does not have Java 11 installed and
Unicode
characters are incomplete.
If you also want to experiment, it is recommended to use the online tool, select the corresponding JDK.
trim
trim()
is the most common way
for Java
developers to remove spaces at the beginning and end of strings.
The usage is also relatively simple:
public class StringTest {
public static void main(String[] args) {
String stringWithSpace = " Hollis Is A Java Coder ";
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:
Before trim : ' Hollis Is A Java Coder '
After trim : 'Hollis Is A Java Coder'
As above, after using
trim
the space content at the beginning and end of the original string is removed.
But I don't know if you've ever thought about what the white space removed by the
trim
method contains?
Are there any other characters besides spaces?
In fact, the blank character removed by trim refers to any character whose ASCII value is less than or equal to 32 ('U'0020'):
It contains characters such as spaces, line breaks, backstags, and so on.
strip()
I wonder if you've noticed that in the release of Java 11, a new strip() method has been added to remove leading and ending spaces from the string.
Now that you have a
trim
method, why add a
strip
This is actually because
trim
method can only remove characters with
ASCII
values less than or equal to 32, but
according to Unicode, there are many other blank characters besides characters in ASCII.
And to recognize these space characters, a new
isWhitespace(int)
method has been added to the
Character
class, starting with Java 1.5. T
his method uses unicode to identify space characters.
You can learn more
unicode
space characters in jkorpela.fi/chars/spaces.html.
The new
strip
method in Java 11 is to use this
Character.isWhitespace(int)
method to determine if they are blank characters and remove them:
Let's look at an example of using strip:
public class StringTest {
public static void main(String args[]) {
String stringWithSpace ='\u2001' + " Hollis Is A Java Coder " + '\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 + "\'");
}
}
We've added a special character before and after the string,
\u2001
is not in
ASCII
and is judged by
Character.isWhitespace
to be a blank character.
The
strip
is then used for processing, and the output is as follows:
' ' is space : true
Before strip : ' Hollis Is A Java Coder '
After strip : 'Hollis Is A Java Coder'
Therefore, the strip method in Java 11 is more powerful than the trim method, which removes many blank characters that are not in ASCII and is judged by the Acter.isWhitespace method.
Above we describe two ways to remove the beginning and end of a string,
trim
and
strip
and compare their differences:
The stripLeading() and stripTrailing () methods were also added in Java 11. The effect is to remove the space at the beginning of the string and the space at the end of the string.
Similar to
strip
method,
stripLeading
stripTrailing
also uses
Character.isWhitespace(int)
to identify blank characters.
The usage is similar to
strip
public class StringTest {
public static void main(String args[]) {
String stringWithSpace ='\u2001' + " Hollis Is A Java Coder " + '\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("Before stripLeading : \'" + stringWithSpace + "\'");
String stringAfterTrim = stringWithSpace.stripLeading();
System.out.println("After stripLeading : \'" + stringAfterTrim + "\'");
}
private static void stripTrailingTest(String stringWithSpace){
System.out.println("Before stripTrailing : \'" + stringWithSpace + "\'");
String stringAfterTrim = stringWithSpace.stripTrailing();
System.out.println("After stripTrailing : \'" + stringAfterTrim + "\'");
}
}
Output:
' ' is space : true
Before stripLeading : ' Hollis Is A Java Coder '
After stripLeading : 'Hollis Is A Java Coder '
Before stripTrailing : ' Hollis Is A Java Coder '
After stripTrailing : ' Hollis Is A Java Coder'
In addition to using
trim
and
strip
there is another way to remove white space characters from strings, which is to replace them with
replace
method.
Replace is added from java 1.5 and can replace each target substring with the specified string.
This method replaces all matching target elements as follows:
public class StringTest {
public static void main(String args[]) {
String stringWithSpace =" Hollis Is A Java Coder ";
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 + "\'");
}
}
outcome:
Before replace : ' Hollis Is A Java Coder '
After replace : 'HollisIsAJavaCoder'
As you can see, the above use
replace
method can replace all the blank characters in the string.
II.
replaceAll
is one of the
most powerful
string manipulation methods added in Java 1.4.
We can use this approach for many purposes.
Using
replaceAll()
method, we can use regular expressions to identify the content of the target character that needs to be replaced.
With regular expressions, you can do many things, such as deleting all spaces, removing opening spaces, deleting end spaces, and so on.
We just need to create the correct regular expression with the correct replacement parameters. Some examples of regular expressions are:
\s+ 所有的空白字符
^\s+ 字符串开头的所有空白字符
\s+$ 字符串结尾的所有空白字符
Note that to add/we have to use escape
\s+
in
java
we have to
\\s+
public class StringTest {
public static void main(String args[]) {
String stringWithSpace =" Hollis Is A Java Coder ";
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 + "\'");
}
}
outcome:
Before replaceAll with ' ': ' Hollis Is A Java Coder '
After replaceAll with ' ': 'HollisIsAJavaCoder'
Before replaceAll with '\s+': ' Hollis Is A Java Coder '
After replaceAll with '\s+': 'HollisIsAJavaCoder'
Before replaceAll with '^\s+': ' Hollis Is A Java Coder '
After replaceAll with '^\s+': 'Hollis Is A Java Coder '
Before replaceAll with '\s+$': ' Hollis Is A Java Coder '
After replaceAll with '\s+$': ' Hollis Is A Java Coder'
As we can see, if you use
replaceAll()
with the appropriate regular expression, it will be a very powerful method.
replaceFirst
method was also added in java 1.4, which replaces only the first match of a given regular expression with a replacement string.
This method is useful if you only need to replace the first occurrence.
For example, if we just need to remove
^\\s+
the leading
\\s+
we can use the .
We can also use this method to remove the end space by
\\s+
the regular expression of . B
ecause this expression will only match the last space of the row.
So the last space is considered the first match for this method.
Let's give an example of removing leading and trailing spaces from a string
public class StringTest {
public static void main(String args[]) {
String stringWithSpace =" Hollis Is A Java Coder ";
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 + "\'");
}
}
outcome:
Before replaceFirst with ' ': ' Hollis Is A Java Coder '
After replaceFirst with ' ': ' Hollis Is A Java Coder '
Before replaceFirst with '\s+': ' Hollis Is A Java Coder '
After replaceFirst with '\s+': 'Hollis Is A Java Coder '
Before replaceFirst with '^\s+': ' Hollis Is A Java Coder '
After replaceFirst with '^\s+': 'Hollis Is A Java Coder '
Before replaceFirst with '\s+$': ' Hollis Is A Java Coder '
After replaceFirst with '\s+$': ' Hollis Is A Java Coder'
This article describes seven ways to remove blank characters from a string.
To remove the blank characters at the beginning of the string directly, you can use
stripLeading
replaceAll
and
replaceFirst
To remove white space characters directly from the end of a string, you can use
stripTrailing
replaceAll
and
replaceFirst
To remove both blank characters at the beginning and end of a string, you can use
strip
trim
To remove all blank characters from a string, you can use
replace
and
replaceAll
Java's 11 new
strip
stripTrailing
and
stripLeading
methods can remove more characters than any other method, and the white space characters he can remove are not limited to characters in
ASCII
but all blank characters in
Unicode
as can be judged by
Character.isWhitespace
Here are 7 ways
W3Cschool编程狮
can remove spaces from String!
Related to the introduction, I hope to help you.