2013-06-20 105 views
1

在我的程序中,我需要从字符串中提取数字,给定的字符串如下所示。我需要从Java中提取字符串中的数字

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

在此先感谢!

+0

使用量词 - '分裂( “\\ S +”)' –

+4

为什么你遍历'hoursPerDay'长度,以及访问'pieces'数组的索引? –

+0

我的不好,那是我正在试验的一段旧代码。 srry。分裂(“\\ s +”)工作完美。非常感谢! Hey MaQy,你是对的!那就是问题 – dimlo

回答

4

此:

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”。这是你在找什么?

+0

是的,先生,非常感谢! – dimlo

+0

不客气,但请按照Rohit Jain的建议修复代码。你不想循环到hoursPerDay.length,是吗? ;-) pieces.length就足够了。 – Paolof76

+0

@Dimlo - 如果这是你的问题的正确答案,你能否接受它。 – selig

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

这将拆分数组,并将数字字符串转换为int,因为它将它们放入int数组中。它会输出你想要的东西,我测试过它 – sunrize920