Splitting and converting String to int

后端 未结 5 1620
再見小時候
再見小時候 2021-01-12 06:23

I have a problem with my code. I read a couple of numbers of a text-file. For example: Textfile.txt

1, 21, 333

With my following code I wan

5条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-12 07:15

    Here's a solution using Java 8 streams:

    String line = "1,21,33";
    List ints = Arrays.stream(line.split(","))
            .map(Integer::parseInt)
            .collect(Collectors.toList());
    

    Alternatively, with a loop, just use parseInt:

    String line = "1,21,33";
    for (String s : line.split(",")) {
        System.out.println(Integer.parseInt(s));
    }
    

    If you really want to reinvent the wheel, you can do that, too:

    String line = "1,21,33";
    for (String s : line.split(",")) {
        char[] chars = s.toCharArray();
        int sum = 0;
        for (int i = 0; i < chars.length; i++) {
            sum += (chars[chars.length - i - 1] - '0') * Math.pow(10, i);
        }
        System.out.println(sum);
    }
    

提交回复
热议问题