There is a stringutils class in spring that provides a rich range of features, such as the string substitution function
/*
*instring the characters to be processed,
*oldpattern, the pattern to replace
*newpattern, the pattern used to replace
For example replace ("ABDC", "B", "E"), then ABDC will become AEDC
*/
public static string replace (string instring, String Oldpattern, String newpattern) {
Determines whether a string is valid, boundary processing
if (!haslength (instring) | |!haslength (oldpattern) | | newpattern = = NULL) {
return instring;
}
StringBuilder sb = new StringBuilder ();
int pos = 0; Our position in the old string
Gets the position of the string that conforms to the old pattern, for example instring = Abxd Oldpattern = A, then index, which is index=0
int index = Instring.indexof (Oldpattern);
int patlen = Oldpattern.length ();
while (index >= 0) {//if matching
Returns a new string that is a substring of this string. The substring starts at the specified Beginindex and continues to the character at index EndIndex-1
Sb.append (instring.substring (POS, index));
Sb.append (Newpattern);//string appended with Newpattern
pos = index + patlen;//where the next match begins
index = Instring.indexof (Oldpattern, POS);
}
Sb.append (Instring.substring (POS));//Append the remaining non-conforming character to the replacement match
Remember to append any characters to the right of a match
return sb.tostring ();
}
***************************************************************************
Remove all the blanks, and the method is implemented as follows
public static string Trimallwhitespace (String str) {
if (!haslength (str)) {
return str;
}
StringBuilder sb = new StringBuilder (str);
int index = 0;
while (Sb.length () > Index) {
if (Character.iswhitespace (Sb.charat (index))) {
Sb.deletecharat (index);
}
else {
index++;
}
}
return sb.tostring ();
}
********************************************************************
Remove the opening and closing spaces from the given string
public static string Trimwhitespace (String str) {
if (!haslength (str)) {
return str;
}
StringBuilder sb = new StringBuilder (str);
while (Sb.length () > 0 && character.iswhitespace (sb.charat (0))) {
Sb.deletecharat (0);
}
while (Sb.length () > 0 && character.iswhitespace (Sb.charat (Sb.length ()-1)) {
Sb.deletecharat (Sb.length ()-1);
}
return sb.tostring ();
}