This article will share a replacement of spaces, carriage returns, line breaks, and tabs in the string using java. For more information, see.
Use the replaceAll method of the String object!
ReplaceAll (String regex, String replacement)
Replace this string with the given replacement string to match each substring of the given regular expression.
Sample Code:
The Code is as follows: |
Copy code |
Public class T3 { Public static void main (String args []) { String str = "aa bb cc"; System. out. println (str. replaceAll ("","")); }} |
Removes spaces at the beginning and end of a string.
The Code is as follows: |
Copy code |
Public class Format { Public static String trim (String s ){ Int I = s. length (); // The Position of the last character of the string Int j = 0; // the first character of the string Int k = 0; // intermediate variable Char [] arrayOfChar = s. toCharArray (); // converts a string to a character array While (j <I) & (arrayOfChar [(k + j)] <= '')) + + J; // determine the number of spaces before the string While (j <I) & (arrayOfChar [(k + I-1)] <= '')) -- I; // determines the number of spaces after the string Return (j> 0) | (I <s. length ()))? S. substring (j, I): s); // return the string after spaces are removed. } Public static void main (String [] args ){ String s = trim ("hello "); System. out. println (s ); } } |
Next we will share a replacement string with all spaces
The Code is as follows: |
Copy code |
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 "; 1. Remove spaces: s = s. replace ('\ s ',''); 2. 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 )*/ } |