Reputation: 73741
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 there would not be any pattern but i need the first 3 digits of the number.
can this be done?
Upvotes: 0
Views: 1827
Reputation: 1329
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);
}
}
Upvotes: 0
Reputation: 23373
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);
Upvotes: 0
Reputation: 11934
"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.
Upvotes: 0
Reputation: 6760
String myFirstThreeDigitsAsStr = String.valueOf(mynumber).substring(0,3)
Upvotes: 0
Reputation: 116266
String firstThreeDigits = number.substring(0, 3);
Upvotes: 0
Reputation: 19971
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.
Upvotes: 2