[英]Splitting and converting String to int
I have a problem with my code. 我的代码有问题。 I read a couple of numbers of a text-file.
我读了几个文本文件。 For example: Textfile.txt
例如:Textfile.txt
1, 21, 333
With my following code I want to split and convert the numbers from String to int. 使用我的以下代码,我想拆分并将数字从String转换为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);
}
I get the result in my console (int): 我在我的控制台(int)中得到了结果:
1 3 9
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)? 我看到数字3是2 + 1的结果,数字9是3 + 3 + 3的结果。我能做什么,在我的控制台(int)中接收以下结果?
1 21 333
/EDIT: I am only allowed to use Java.lang and Java.IO /编辑:我只允许使用Java.lang和Java.IO
Here's a solution using Java 8 streams: 这是使用Java 8流的解决方案:
String line = "1,21,33";
List<Integer> ints = Arrays.stream(line.split(","))
.map(Integer::parseInt)
.collect(Collectors.toList());
Alternatively, with a loop, just use parseInt
: 或者,使用循环,只需使用
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);
}
您可以使用Integer.valueOf(retval)
或Integer.parseInt(retval)
A couple of problems: 一些问题:
factor
should be multiplied by 10 in every loop factor
应该在每个循环中乘以10 answer
and factor
should be re-initialized between the numbers you're parsing: answer
和factor
: String line = "1,21,333";
for (String retval : line.split(",")) {
int answer = 0;
int factor = 1;
for (int j = retval.length() - 1; j >= 0; j--) {
answer = answer + (retval.charAt(j) - '0') * factor;
factor *= 10;
}
System.out.println(answer);
answer = (answer - answer);
}
OUTPUT OUTPUT
1
21
333
好吧,你可以回答一个字符串,并在for循环后将其转换为整数。
For folks who come here from a search, this function takes a separated values string and delimiter string and returns an integer array of extracted values. 对于从搜索到此处的人来说,此函数采用分隔值字符串和分隔符字符串,并返回提取值的整数数组。
int[] parseStringArr( String str, String delim ) {
String[] strArr = str.trim().split(delim);
int[] intArr = new int[strArr.length];
for (int i = 0; i < strArr.length; i++) {
String num = strArr[i].trim();
intArr[i] = Integer.parseInt(num);
}
return intArr;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.