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

 ̄綄美尐妖づ 提交于 2019-12-13 15:35:07

问题


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

回答1:


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



回答2:


You can use regular expressions (regex).

A simple example of breaking with commas:

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



回答3:


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



回答4:


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);



回答5:


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]);
}



回答6:


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

If you want to add additional delimiters, e.g. :, add to the delimiter set, e.g. "([\\-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");
    }
}


来源:https://stackoverflow.com/questions/9180849/what-is-the-best-way-to-extract-this-int-from-a-string-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!