[英]How to find integer value of specific characters in a Java string array?
I am using the following code to take a string value like 9s or 4c that is located within a string array and find just the integer value of the first character. 我正在使用以下代码来获取位于字符串数组内的字符串值(如9s或4c),并找到第一个字符的整数值。 I would also like to be able to use this for string values with multiple numbers like 10s or 13c.
我还希望能够将其用于具有多个数字(例如10s或13c)的字符串值。
total = total + Integer.parseInt(a[i].substring(0)) + 1;
This gives me a number format exception. 这给了我一个数字格式的例外。 Any ideas what I might be doing wrong?
有什么想法我可能做错了吗?
This will work 这会起作用
public static void getIntVal() {
String text = "123cc";
String numOnly = text.replaceAll("\\D+", "");
int numVal = Integer.valueOf(numOnly);
System.out.println(numVal);
}
IF some one want to use as double, you can do it as follows 如果有人想使用双倍,则可以按照以下步骤进行操作
String text = "123.0114cc";
String numOnly = text.replaceAll("\\p{Alpha}","");
double numVal = Double.valueOf(numOnly);
System.out.println(numVal);
Ruchira's solution prescribes removal of non digit characters; Ruchira的解决方案规定删除非数字字符。 which in your setup seems right.
在您的设置中看起来是正确的。 However, her solution is invalid if the numbers are floats or doubles as
shreyansh jogi
questions. 但是,如果数字如
shreyansh jogi
问题那样为浮点数或双精度数,则她的解决方案无效。
Implementing Ruchira's thought solution properly, this would solve your problem... 正确实施Ruchira的思想解决方案,可以解决您的问题...
String text = "123.0121cc";
String numOnly = text.replaceAll("\\p{Alpha}", "");
If you know what to expect, say double
: double numVal = Double.valueOf(numOnly); 如果您知道会发生什么,请说
double
:double numVal = Double.valueOf(numOnly); System.out.println(numVal); System.out.println(numVal);
Otherwise.. if you don't know whether the rest of the text is integer
or double
, this would help you: 否则..如果您不知道其余文本是
integer
还是double
,这将对您有所帮助:
if(numOnly.contains(".")) {
double numVal = Double.valueOf(numOnly);
System.out.println(numVal);
} else {
int numVal = Integer.valueOf(numOnly);
System.out.println(numVal);
}
total = total + Integer.parseInt(a[i].substring(0,a[i].length()-1));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.