Sometimes, there is a case, it may not be the space, rather could be non-breakable space
, n space
, m space
etc.,
In wich the trim()
will not work for some characters.
Make sure the last character is space.
If the last character is not space, then you could write your own logic to do that.
String text = " my text ";
char[] trimChars = {'\u00A0', ' '};//Add anything else you like to trim.
bool isSpaceBefore = false, isSpaceAfter = false;
do {
isSpaceAfter = false;
isSpaceBefore = false;
for(int c=0; c<trimChars.length; c++) {
isSpaceBefore = text.indexOf(trimChars[c]) == 0;
isSpaceAfter = text.lastIndexOf(trimChars[c]) == text.length-1;
}
if(isSpaceAfter) text = text.substring(0, text.length-1);
if(isSpaceBefore) text = text.substring(1);
}
while(isSpaceBefore || isSpaceAfter);
as a simplified version, you could use a find and replace also. But note that the replace will replace any characters that match even if they are in the middle of the string.