【问题标题】:Get multiple Integer values from a String?从字符串中获取多个整数值?
【发布时间】:2015-09-18 19:33:55
【问题描述】:

[不是将String 转换为Integer]

我需要从String 中获取一些数字,这是控制台命令的一行。

例如:

String str = "234 432 22 66 8 44 7 4 3 333";

如何获取每个 Integer 值并将它们放入数组中? 数字的顺序并不重要,因为String 可能是:

String str = "34 434343 222";

String str = " 1 2 3 4 5 6 7";

另外,在这两种情况下如何获取数字(带有一个或多个空白字符):

String str = "2 2 44 566";

 String str = "2121     23  44 55 6   58";

【问题讨论】:

标签: java arrays string int


【解决方案1】:

如果你想捕获用空格分隔的数字,那么你可以这样做:

String str = "234 432 22 66 8 44 7 4 3 333";

String[] strArr = str.split("\\s+");
// strArr => ["234", "432", "22", "66", "8", "44", "7", "4", "3", "333"]

更新:正如 Evan LaHurd 在他的评论中指出的那样,您可以处理数组值,如果您想将字符串转换为整数,您可以使用:

int n = Integer.parseInt("1234");
// or
Integer x = Integer.valueOf("1234");

IDEOne Example

【讨论】:

  • 那么如果你想使用Integer对象,你可以在数组中的每个String上使用Integer.parseInt(String s)
  • 所以我只能使用 "\\s+" 处理多个 >1 的空格?
  • @f.stacchietti 确切地说,\s+ 是一个正则表达式,用于匹配 1 到多个空格并使用它们来拆分您的字符串。在java中你必须转义反斜杠,因此\\s+
【解决方案2】:

你可以这样做。

    String str = "234 432 22 66 8 44 7 4 3 333";

    String[] stringArray = str.trim().split("\\s+");//remove any leading, trailing white spaces and split the string from rest of the white spaces

    int[] intArray = new int[stringArray.length];//create a new int array to store the int values

    for (int i = 0; i < stringArray.length; i++) {
        intArray[i] = Integer.parseInt(stringArray[i]);//parse the integer value and store it in the int array
    }

【讨论】:

  • 这将在前导空格上失败(参见第三个示例)。
  • 是的!感谢您的帮助,我为此花费了最后 1 小时,哈哈。再次感谢您!
【解决方案3】:

在空格上使用split 并将子字符串解析为整数:

String str = "   2121     23  44 55 6   58   ";

// To list
List<Integer> numberList = new ArrayList<Integer>();
for (String numberText : str.trim().split("\\s+"))
    numberList.add(Integer.valueOf(numberText));

// To array
String[] numberTexts = str.trim().split("\\s+");
int[] numberArray = new int[numberTexts.length];
for (int i = 0; i < numberTexts.length; i++)
    numberArray[i] = Integer.parseInt(numberTexts[i]);

// Show result
System.out.println(numberList);                   // [2121, 23, 44, 55, 6, 58]
System.out.println(Arrays.toString(numberArray)); // [2121, 23, 44, 55, 6, 58]

【讨论】:

    【解决方案4】:

    如果您只想将字符串的数字放入数组中,也可以使用 Scanner 类中的“nextInt()”方法。

    String str = "2 56  73     4           9   10";
    Scanner scanner = new Scanner(str);
    
    List<Integer> integers = new ArrayList<Integer>(0);
    While( scanner.hasNext() )   // checks if theres another number to add
        integers.add( scanner.nextInt() );
    

    您还可以使用“hasNextInt()”避免非数字字符:

    while( scanner.hasNext(){
        if( scanner.hasNextInt() )
            integers.add( scanner.nextInt() );
    }
    

    请记住,如果您希望它成为一个数组,您仍然需要转换列表或以不同的方式将数字放在一起。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-07-24
      • 2020-04-28
      • 1970-01-01
      • 1970-01-01
      • 2013-07-09
      • 1970-01-01
      • 2022-09-28
      • 1970-01-01
      相关资源
      最近更新 更多