从Java中的字符串中提取此int的最佳方法是什么? [英] What is the best way to extract this int from a string in Java?

查看:101
本文介绍了从Java中的字符串中提取此int的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是我可能获得的一些输入的示例

Here are examples of some input that I may be given

1,4
34,2
-99,20

等。

因此包括负值,并且可以使用1,2,3等数字。逗号不是唯一的分隔符,只是一个例子。但非整数值是parseInt不起作用的原因。我能编码什么才能解析上面的3个输入以便我得到这个?

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


推荐答案

使用此代码:

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

输出:

1
34
-99

这篇关于从Java中的字符串中提取此int的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆