Java 获取数字字符串的一部分
假设我有一个数字字符串Java 获取数字字符串的一部分,java,string,Java,String,假设我有一个数字字符串“1234567890”,从中我想得到数字字符串“123”的前3位数字。我所看到的一切都需要某种模式来分割字符串,但是数字可以是任何数字,因此不会有任何模式,但我需要数字的前3位数字 可以这样做吗?您需要字符串上的子字符串方法。有关详细信息,请参阅。似乎可以使用子字符串: String firstThreeDigits = number.substring(0, 3); number.substring(0, 3); “1234567890”。子字符串(0,3)是您所需
“1234567890”
,从中我想得到数字字符串“123”
的前3位数字。我所看到的一切都需要某种模式来分割字符串,但是数字可以是任何数字,因此不会有任何模式,但我需要数字的前3位数字
可以这样做吗?您需要字符串上的
子字符串
方法。有关详细信息,请参阅。似乎可以使用子字符串:
String firstThreeDigits = number.substring(0, 3);
number.substring(0, 3);
“1234567890”。子字符串(0,3)代码>是您所需要的。
该方法返回一个字符串,该字符串从输入的第0个索引开始,在索引3结束。如果该字符串包含一个数字,如您的示例所示,您可以简单地使用该方法:
如果您的意思是需要从字符串中提取第一个数字并获取前3个字符,则可以执行以下操作:
public class NumberFinder {
public int findNumber(String string) throws NumberFormatException{
String regex = "\\d+"; //matches one or more digits
Pattern myPattern = Pattern.compile(regex);
Matcher myMatcher = myPattern.matcher(string);
String numString = new String();
while (myMatcher.find()) {
numString = myMatcher.group(); //returns whole match
}
String numSub = numString.length() >= 3 ? numString.substring(0, 3).toString() : "Not Enough Numbers";
System.out.println(string);
System.out.println(numString);
System.out.println(numSub);
return Integer.parseInt(numSub);
}
}
public static void main(String[] args) {
String string = "ABCD1242DBG";
try {
new NumberFinder().findNumber(string);
} catch (NumberFormatException e) {
System.out.println("Not enough numbers in " + string);
}
}
好吧,我(和另外两个人)已经发布了简单的答案,但我猜还有更多。您需要验证您的输入实际上是一个数字,还是进行其他处理?
String number = "12345678";
String firstThreeDigits = number.substring(0, 3);
public class NumberFinder {
public int findNumber(String string) throws NumberFormatException{
String regex = "\\d+"; //matches one or more digits
Pattern myPattern = Pattern.compile(regex);
Matcher myMatcher = myPattern.matcher(string);
String numString = new String();
while (myMatcher.find()) {
numString = myMatcher.group(); //returns whole match
}
String numSub = numString.length() >= 3 ? numString.substring(0, 3).toString() : "Not Enough Numbers";
System.out.println(string);
System.out.println(numString);
System.out.println(numSub);
return Integer.parseInt(numSub);
}
}
public static void main(String[] args) {
String string = "ABCD1242DBG";
try {
new NumberFinder().findNumber(string);
} catch (NumberFormatException e) {
System.out.println("Not enough numbers in " + string);
}
}