-1
String m1 = nextLine[6]; //"9602612325 "
m1 = m1.trim();                                  
if(m1 != null && !m1.isEmpty()){
      mob1 = Double.parseDouble(m1);
}else{
      mob1 = 0; 
}

I am trying to remove the space in

String m1 = "9602612325 ";

I've gone through the following links string trim function and string pool but still couldn't find the answer. Can anyone help me?

Community
  • 1
  • 1
User
  • 69
  • 1
  • 13

2 Answers2

1

Try this :

String m1 = "9602612325 ";
if(! Strings.isNullOrEmpty(m1)){ // Google Guava's utility class --> Strings
     m1 = m1.trim();
     try{
      mob1 = Double.parseDouble(m1);
      }
     catch(NumberFormatException e){
       mob1=0;
      }
}
else{
    mob1=0;
}                                      

Note : You can also check manually for null and empty like this

if("".equals(m1)){    // here you need not to check for null seperately
 //do Whatever you need to do 
}
Neeraj Jain
  • 7,643
  • 6
  • 34
  • 62
1

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.

Vinod Kumar
  • 981
  • 1
  • 6
  • 14