简体   繁体   中英

What is the best way to extract this int from a string in Java?

Here are examples of some input that I may be given

1,4
34,2
-99,20

etc.

Therefore negative values are included and 1, 2, 3, etc digits are possible. Commas are not the only delimiters, just an example. But Non integer values are the reason parseInt won't work. What can I code that will allow me to parse the above 3 inputs so that I get this?

1
34
-99

You can use regular expressions (regex).

A simple example of breaking with commas:

String[] values = string.split(",")
for (String a : values) {
    Integer.parseInt(a);
}

Use this code:

String str = "1,4 34,2 -99,20";
String[] arr = str.split("\\D+(?<![+-])");
for (int i=0; i<arr.length; i+=2)
    System.out.println(Integer.parseInt(arr[i]));

OUTPUT:

1
34
-99

This is a very open question... I will suggest that you first go through your string, and format all the numbers correctly substituting all the commas for dots... Then you need to split it, and then you need to parse each value.

For each step you can find a lot of help googling.

ie.

  • Step 1. String substitution java
  • Step 2. String split java
  • Step 3. String to int java

You can replace all characters except digits with an empty string and then do a parseInt

String intStr = inputStr.replaceAll("[^0-9]+","");
int i = Integer.parseInt(intStr);

If you only use commas, you could do

String numbers = "1,34,-99";
String[] splitNums = numbers.split(",");
int[] ints = null;
for(int i = 0; i < splitNums.length(); i++) 
{
    ints[i] = Integer.valueOf(splitNums[i]);
}

If you want input to be valid only if there is a delimiter, use "([\\\\-0-9]*)[,]+.*" instead.

If you want to add additional delimiters, eg : , add to the delimiter set, eg "([\\\\-0-9]*)[,|:]+.*"

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Test {
   public static void main(String args[]) {
        try {
            String s1 = "-99,20";
            System.out.println(getNumber(s1));

            s1 = "1,4";
            System.out.println(getNumber(s1));
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public static int getNumber(String s1) throws Exception {
        Pattern pattern = Pattern.compile("([\\-0-9]*)[,]*.*");
        Matcher m = pattern.matcher(s1);
        if(m.find()) {
            return Integer.parseInt(m.group(1));
        } 

        throw new Exception("Not valid input");
    }
}

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