1. String. trim ()
Trim () is to remove spaces at the beginning and end
2. str. replace ("", ""); remove all spaces, including the beginning, end, and middle.
| The Code is as follows: |
|
|
String str = "hell o ";
String str2 = str. replaceAll ("","");
System. out. println (str2 );
|
3. Or replaceAll ("+", ""); remove all spaces.
| The Code is as follows: |
|
|
4. str =. replaceAll ("s *",""); |
Can replace most of the white space characters, not limited to spaces
S can match any of the spaces, tabs, page breaks, and other blank characters.
Or the following code can also remove all spaces, including the beginning, end, and middle.
| The Code is as follows: |
|
|
Public String remove (String resource, char ch)
{
StringBuffer buffer = new StringBuffer ();
Int position = 0;
Char currentChar;
While (position <resource. length ())
{
CurrentChar = resource. charAt (position ++ );
If (currentChar! = Ch) buffer. append (currentChar);} return buffer. toString ();
} |
Let's take a look at the instance.
| The Code is as follows: |
|
Import java. util. regex. Matcher;
Import java. util. regex. Pattern;
/**
* @ Author lei
* 2011-9-2
*/
Public class StringUtils {
Public static String replaceBlank (String str ){
String dest = "";
If (str! = Null ){
Pattern p = Pattern. compile ("s * | t | r | n ");
Matcher m = p. matcher (str );
Dest = m. replaceAll ("");
}
Return dest;
}
Public static void main (String [] args ){
System. out. println (StringUtils. replaceBlank ("just do it! "));
}
/*-----------------------------------
Stupid method: String s = "the String you want to remove ";
. Remove spaces: s = s. replace ('s ','');
. Remove the carriage return: s = s. replace ('n ','');
In this way, the space and press ENTER can be removed, and others can be taken as well.
Note: n press enter (u000a)
T horizontal tab (u0009)
S space (u0008)
R line feed (u000d )*/
} |