簡體   English   中英

如何將字符串轉換為 Integer 並添加它 arrayList

[英]How to convert string to Integer and add it arrayList

如何將字符串轉換為整數,如何使用這些整數創建 ArrayList?
我的字符串僅包含數字,並且我的數字之間存在差距。
例如,給定字符串st1 = "1 2 3 4"str2 = "11 20 23 24"
我需要一個ArrayList for str1例如"1, 2, 3, 4"
我嘗試使用Integer.parseInt(str1)Integer.valueOf(str1)但這些適用於str1 = "1234"

此方法會將此類字符串轉換為ArrayList<Integer>

public static ArrayList<Integer> toStringList(String string){
    String ints[]=string.split(" ");
    ArrayList<Integer> list=new ArrayList<>();
    for(String str:ints){
        list.add(Integer.parseInt(str));
    }
}

請記住,此方法會將您的字符串(例如“1 2 3 4”)轉換為具有 1 到 4 個值的列表。 如果要將其轉換為1234 ,則應首先刪除空格:

String str="1 2  3 4  ";
str = str.replaceAll(" ","");
Integer number=Integer.parseInt(str); //equals 1234

您可以這樣做將字符串列表轉換為整數。 關注@Tim 代碼

        String st1 = "1 2 3 4";
        String[] array = st1.split("\\s+");
        List<Integer> integers = Arrays.stream(array)
                .map(Integer::valueOf).collect(Collectors.toList());
        System.out.println(integers);
        //[1, 2, 3, 4]

此代碼會將在字符串中找到的任何數字轉換為其 integer。 這將解決您的問題。

String str = "1 2 3 4 5 11 12 13 14 15 1 12 123 1234 12345";
int stringLength = str.length();
int[] answer;
String intBuffer = "";
int j = 0, countSpaces = 0;

for (int i = 0; i < stringLength; i++) {
    if (str.charAt(i) == ' ') countSpaces++;
}
answer = new int[countSpaces + 1];

for (int i = 0; i < stringLength; i++) {
    if (str.charAt(i) != ' ') {
        intBuffer = intBuffer + str.charAt(i);
        if (i == stringLength - 1)
            answer[j] = Integer.parseInt(intBuffer);
    } else {
        answer[j++] = Integer.parseInt(intBuffer);
        intBuffer = "";
    }
}
for (int i = 0; i < answer.length; i++)
    System.out.println(answer[i] + " ");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM