Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse String containing '+' symbol [duplicate]

Tags:

java

I have a string which has numbers.

I have a code like this,

    String tempStr = "+123";
    NumberFormat numformat = NumberFormat.getNumberInstance();
    numformat.setParseIntegerOnly(true);
    try {
        int ageInDays = Integer.parseInt(tempStr);
        System.out.println("the age in days "+ageInDays);
    } catch (NumberFormatException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

It is working fine for the number with negative symbols.But I can't do it for number with '+' symbol. It throws NumberFormatException.

So how can I parse a number with '+' symbol from a string?

like image 981
Sankar Avatar asked Jul 24 '15 01:07

Sankar


People also ask

How do you check whether string contains any duplicate characters?

To find the duplicate character from the string, we count the occurrence of each character in the string. If count is greater than 1, it implies that a character has a duplicate entry in the string. In above example, the characters highlighted in green are duplicate characters.

How do you check if a character is repeated in a string Java?

println("Write the character: "); String character = in. next(); if (chain. contains(character)) { cont = cont + 1; } System.

How do you parse a string?

To parse a string in Java, you can use the Java String split() method, Java Scanner class, or StringUtils class. For parsing a string based on the specified condition, these methods use delimiters to split the string.


1 Answers

In the case you are using Java 7 or higher I would recommend using java.lang.Long; or java.lang.Integer; (if you are sure that you will have to parse integers).

It works for both cases.

Later edit: I didn't see that you were using Integer.parseInt();

Therefore I assume that you have Java 6 or less.

In this case try calling the following method before the line with Integer.parseInt(tempStr); to remove the + in case it exists:

private static String removePlusSignIfExists(String numberAsString) {
    if(numberAsString == null || numberAsString.length() == 0){
        return numberAsString;
    }

    if(numberAsString.charAt(0) == '+'){
        return numberAsString.substring(1, numberAsString.length());
    } else {
        return numberAsString;
    }
}
like image 59
Flowryn Avatar answered Nov 06 '22 07:11

Flowryn