[英]I need to extract numbers from a String in Java
在我的程序中,我需要从String中提取数字,给定的字符串如下。
String numberOfHours = "12.0 8.0 7.0 7.0 10.0 8.0 0.0 2.0";
我需要将每个值提取到一个数组中。 当我使用String类中的split方法时,我得到一个空值,而且我没有得到数组中的所有数字。 这是代码。
String pieces[] = numberOfHours.split(" ");
for(int i = 0 ; i < hoursPerDay.length ; i++){
System.out.println(pieces[i]);
}
提前致谢!
这个:
String numberOfHours = "12.0 8.0 7.0 7.0 10.0 8.0 0.0 2.0";
String pieces[] = numberOfHours.split("\\s+");
System.out.println(pieces.length);
打印:“8”。 这是你在找什么?
public static void main(String[] args){
String numberOfHours = "12.0 8.0 7.0 7.0 10.0 8.0 0.0 2.0";
String pieces[] = numberOfHours.split("\\s+");
int num[] = new int[pieces.length];
for(int i = 0; i < pieces.length; i++){
//must cast to double here because of the way you formatted the numbers
num[i] = (int)Double.parseDouble(pieces[i]);
}
for(int i = 0; i < num.length; i++){
System.out.println(num[i]);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.