简体   繁体   中英

Extracting Ints from Strings in Java

I'm trying to write a method which takes a String, looks for Ints in it and then adds them together.

for example:

    String s = "five5six66"

should return 5+66 = 71 or:

    String s = "1ciao2three3"

should return 1+2+3 = 6

The following is what I wrote already, but when I run it I get a

    NumberFormatException

code (Update 1):

    public static int addNumbers(String s) {
    String numbers="";
    int addNumbers = 0;
    int i;
    char c;

    for (i=0; i<s.length(); i++) {
        if (s.charAt(i)>='0' && s.charAt(i)<='9') {
            c = s.charAt(i);
            while (i<s.length()-1) {
                if (s.charAt(i+1)>='0' && s.charAt(i+1)<='9')
                    numbers = numbers.valueOf(c + s.charAt(i+1));
                addNumbers = addNumbers + Integer.parseInt(numbers);
            }
            addNumbers = addNumbers + Character.getNumericValue(c);
        }
    }
    return addNumbers;
}

Hopefully you can help me fix this code and please, let me understand what I did wrong!

Also can I expand it so if I have a String like:

    String s = "hi123and27"

I can get 123+27 = 150?

Because my code is limited to a 2 digit number as it is now.

I would suggest using REGEX to address your requirements:

you will need:

  1. the REGEX pattern: "\\d+"
  2. an accumulator that is concatenating the value you get of the given String

Example:

public static void main(String[] args) {
    String s = "hi123and27";
    Pattern p = Pattern.compile("\\d+");
    Matcher m = p.matcher(s);
    int accumulator  = 0;
    while (m.find()) {
        accumulator  += Integer.parseInt(m.group());
    }
    System.out.println("final result: " + accumulator );
}

Regex + Java 8 streams:

public static int addNumbers(String str) {
    return Arrays.stream(str.replaceAll("[^0-9]", " ").split(" "))
            .filter(s -> !s.isEmpty())
            .mapToInt(Integer::parseInt)
            .sum();
}

EDIT regarding recommendations is the comments:

public static int addNumbers(String str) {
    return Arrays.stream(str.split("[^0-9]+"))
            .filter(s -> !s.isEmpty())
            .mapToInt(Integer::parseInt)
            .sum();
}

Try this

public static void main(String [] args){

    String string = "hi123and27";

    int size = string.length();

    int sum = 0;
    StringBuilder val = new StringBuilder();

    for (int idx = 0; idx < size; idx++) {
        Character character = string.charAt(idx);

        if (Character.isDigit(character)) {
            val.append(character);

            //if last character is a digit
            if((idx+1 == size) && val.length() > 0)
                sum += Integer.parseInt(val.toString());

        }else{
            if(val.length() > 0)
                sum += Integer.parseInt(val.toString());

            //reset the val for digits between characters for it to store the next sequence
            val.setLength(0);
        }
    }

    System.out.println("The sum is : " + sum);
}

You should try this one.

public static int addNum(String text){
    String numbers = "";
    int finalResult = 0;

    for(int i=0;i < text.length();i++){

        if(isNumeric(text.substring(i, i + 1)))
        {
            numbers += text.substring(i, i + 1);

            if(i==text.length()-1) {
                finalResult += Integer.parseInt(numbers); 
            }
        }else {
            if(!numbers.equals("")){
                finalResult += Integer.parseInt(numbers);
                numbers = "";
            }
        }
    }
    return finalResult;
}

public static boolean isNumeric(String str)  
{  
  try{  
    int d = Integer.parseInt(str);  
  }  
  catch(NumberFormatException ex){  
    return false;  
  }
  return true;  
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM