[Solved] I have a Java String, i need to extract only the first digits from it. for example the String: “2 fishes 3” I want to get only: “2”


This should work 🙂

String num1 = mEtfirst.getText().toString(); 
char[] temp = num1.toCharArray();
int i=0;
num1="";

while(Character.isDigit(temp[i]))
     num1=num1+Character.toString(temp[i++]);

This converts the string to a character array, checks the array character by character, and stores it in num1 until a non-digit character is encountered.

Edit:

Also, if you want to convert num1 to an integer, use:

num1=Integer.parseInt(num1);

solved I have a Java String, i need to extract only the first digits from it. for example the String: “2 fishes 3” I want to get only: “2”