从字符串中提取整数到数组中

我需要从字符串中提取整数到数组中。


我已经得到了integers,但我无法将它们放入数组中。


public static void main(String[] args) {

    String line = "First number 10, Second number 25, Third number 123";

    String numbersLine = line.replaceAll("[^0-9]+", "");

    int result = Integer.parseInt(numbersLine);


    // What I want to get:

    // array[0] = 10;

    // array[1] = 25;

    // array[2] = 123;

}


杨魅力
浏览 218回答 3
3回答

波斯汪

假设你有一个像 "10, 20, 30" 这样的字符串,你可以使用以下内容:String numbers = "10, 20, 30";String[] numArray = nums.split(", ");ArrayList<Integer> integerList = new ArrayList<>();for (int i = 0; i < x.length; i++) {&nbsp; &nbsp; integerList.add(Integer.parseInt(numArray[i]));}

LEATH

不是用空字符串替换字符,而是用空格替换。然后分裂它。import java.util.ArrayList;import java.util.List;public class Main {&nbsp; &nbsp; public static void main(String[] args) {&nbsp; &nbsp; &nbsp; &nbsp; String line = "First number 10, Second number 25, Third number 123 ";&nbsp; &nbsp; &nbsp; &nbsp; String numbersLine = line.replaceAll("[^0-9]+", " ");&nbsp; &nbsp; &nbsp; &nbsp; String[] strArray = numbersLine.split(" ");&nbsp; &nbsp; &nbsp; &nbsp; List<Integer> intArrayList = new ArrayList<>();&nbsp; &nbsp; &nbsp; &nbsp; for (String string : strArray) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (!string.equals("")) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println(string);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; intArrayList.add(Integer.parseInt(string));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; // what I want to get:&nbsp; &nbsp; &nbsp; &nbsp; // int[0] array = 10;&nbsp; &nbsp; &nbsp; &nbsp; // int[1] array = 25;&nbsp; &nbsp; &nbsp; &nbsp; // int[2] array = 123;&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java