将String拆分并转换为int [英] Splitting and converting String to int

查看:70
本文介绍了将String拆分并转换为int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码有问题.我读了几个文本文件.例如:Textfile.txt

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

1, 21, 333

使用以下代码,我想将数字拆分并将其从String转换为int.

With my following code I want to split and convert the numbers from String to int.

int answer = 0;
int factor = 1;

// Splitting and deleting the "," AND converting String to int.
for (String retval : line.split(",")) {
    for (int j = retval.length() - 1; j >= 0; j--) {
        answer = answer + (retval.charAt(j) - '0') * factor;
        factor *= 1;
    }
    System.out.println(answer);
    answer = (answer - answer);
}

我在控制台(int)中得到了结果:

I get the result in my console (int):

1 3 9

我看到数字3是2 + 1的结果,数字9是3 + 3 + 3的结果.我该怎么办才能在控制台(int)中收到以下结果?

I see that the number 3 is a result of 2 + 1, and the number 9 is a result of 3 + 3 + 3. What can I do, to receive the following result in my console (int)?

1 21 333

/只允许我使用Java.lang和Java.IO

/ I am only allowed to use Java.lang and Java.IO

推荐答案

以下是使用Java 8流的解决方案:

Here's a solution using Java 8 streams:

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


或者,使用循环,只需使用 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);
}

这篇关于将String拆分并转换为int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆