[英]How to parse an int from a string java?
I'm trying to parse an int from a dummy String for test reasons. 由于测试原因,我试图从虚拟String解析一个int。 The string will be:
字符串将是:
String numOfStudents = "Number of Students: 5";
I want to parse this String, ensuring it contains the line 'Number of Students' as well as finding out the int value. 我想解析此String,确保它包含“ Number of Students”行,并找出int值。
How can I achieve this? 我该如何实现? I need the int value to compare it to another int value.
我需要将int值与另一个int值进行比较。
Thanks 谢谢
final String NUM_OF_STUDENTS = "Number of Students: ";
String numOfStudents = "Number of Students: 5";
int lastIndex = numOfStudents.lastIndexOf(NUM_OF_STUDENTS);
if (lastIndex != -1){
String number = numOfStudents.substring((lastIndex + (NUM_OF_STUDENTS.length())) , numOfStudents.length());
Integer yourResultNumber = Integer.parseInt(number);
System.out.println(yourResultNumber);
}
Since Integer cannot parse String values it throws NumberFormatException
because numbers are expected as input, I would suggest you as you have static type of Strings use like this: 由于Integer无法解析String值,因此会引发
NumberFormatException
因为期望将数字作为输入,因此我建议您使用静态类型的String,如下所示:
String numOfStudents = "Number of Students: 5";
String[] p = numOfStudents.split(":");
Integer i= Integer.parseInt(p[1].trim());
System.out.println(i);
As, p[0]
contain String (label) and p[1]
contain its value. As,
p[0]
包含字符串(标签), p[1]
包含其值。 You can use it later if you want. 如果需要,可以稍后使用。
String numOfStudents = "Number of Students: 55546";
int lastIndex = numOfStudents.lastIndexOf(" ");
if(lastIndex > -1 && lastIndex+1 < numOfStudents.length()) {
String num = numOfStudents.substring(lastIndex+1);
System.out.println(Integer.parseInt(num));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.