I used the most simple
What is online search? replace ("", "") is inexplicable.
You must return a value when using the replaceAll ("", "") method, similar
The Code is as follows:
String str = "a B C D E ";
Str = str. replaceAll ("","");
In this way, the space is deleted. You may have used the replaceAll ("", "") method, but no value is returned.
Later, the following code was found in the website search:
The Code is as follows:
Import java. util. regex. Matcher;
Import java. util. regex. Pattern;
Public class StringUtil {
Public static void replaceBlank ()
{
Pattern p = Pattern. compile ("s * | t | r | n ");
String str = "I am a, I am Hello OK, n new line ffdsa! ";
System. out. println ("before:" + str );
Matcher m = p. matcher (str );
String after = m. replaceAll ("");
System. out. println ("after:" + after );
}
Public static void main (String [] args ){
ReplaceBlank ();
}
}
The above code can contain spaces, carriage returns, line breaks, and tabs in strings.
I Will google it again. This is exactly what I want, because I don't want to delete any content except spaces.
The Code is as follows:
Package com. sharell. Info;
Import java. util. ArrayList;
Import java. util. regex. Matcher;
Import java. util. regex. Pattern;
Public class DelSpace {
Public static void main (String [] args ){
String str = "wo shi zhong guo ren ";
SameResult (str );
}
Private static void sameResult (String str ){
System. out. println (delByPattern (str ));
System. out. println (delByRegex (str ));
System. out. println (delBySB (str ));
System. out. println (delByArr (str ));
}
Public static String delByPattern (String str ){
Pattern p = Pattern. compile ("{2 ,}");
Matcher m = p. matcher (str );
String result = m. replaceAll ("");
Return result;
}
Private static String delByRegex (String str ){
String [] arr = str. split ("+ ");
String result = "";
For (int I = 0; I <arr. length; I ++ ){
Result + = arr [I] + "";
}
If (! Str. endsWith ("")){
Result = result. substring (0, result. length ()-1 );
}
Return result;
}
Public static String delBySB (String str ){
StringBuffer sb = new StringBuffer (str );
For (int index = 0; index <sb. length (); index ++ ){
If (index <sb. length ()-1 & sb. charAt (index) = ''& sb. charAt (index + 1) = ''){
Sb. deleteCharAt (index + 1 );
Index --;
}
}
Return sb. toString ();
}
Private static String delByArr (String str ){
Char [] arr = str. toCharArray ();
String result = "";
ArrayList <Character> al = new ArrayList <Character> ();
For (int I = 0; I <arr. length; I ++ ){
If (I <(arr. length-1) & arr [I] = ''& arr [I + 1] = ''){
Continue;
}
Else {
Al. add (arr [I]);
}
}
Al. trimToSize ();
For (int I = 0; I <al. size (); I ++ ){
Result + = al. get (I );
}
Return result;
}
}