getting part of a number string
lets say i have a number string "1234567890"
and out of that i want to get the first 3 digits from the number string "123"
. everything i have looked at needs some sort of pattern to split a string but the number could be any number so ther开发者_运维问答e would not be any pattern but i need the first 3 digits of the number.
can this be done?
You need the substring
method on String. See http://download.oracle.com/javase/6/docs/api/java/lang/String.html#substring%28int,%20int%29 for details.
String firstThreeDigits = number.substring(0, 3);
Seems like you could just use a substring:
number.substring(0, 3);
String myFirstThreeDigitsAsStr = String.valueOf(mynumber).substring(0,3)
"1234567890".substring(0, 3);
is what you need.
That method returns a String that starts at the 0th index of your input and ends at index 3.
If the string contains a number, like your example you can simply use the substring method:
String number = "12345678";
String firstThreeDigits = number.substring(0, 3);
If you mean you need grab the first number out of a String and get the first 3 characters you could do this:
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);
}
}
精彩评论