1

this is my code :

String addchar = "";
String tempchar;
int len = strline.length();
char[] chars = strline.toCharArray();
int amount = 0;

for (int i = 0; i < len; i++) {
    tempchar = String.valueOf(chars[i]);
    if (tempchar == "0" || tempchar == "1" || tempchar == "2" || tempchar == "3" || tempchar == "4" || tempchar == "5" || tempchar == "6" || tempchar == "7" || tempchar == "8" || tempchar == "9") {
        addchar=tempchar+addchar;
    }
}

amount=Integer.parseInt(addchar);

but when run this code , I see that amount is empty! I want to extract , the number that there is in strline

Matthias F.
  • 147
  • 2
  • 13
Azade
  • 359
  • 2
  • 15

3 Answers3

1

try this use Matcher

  Matcher matcher = Pattern.compile("\\d+").matcher("a22dsdddd212");
while(matcher.find()) {
    Log.e("number :-> ",matcher.group()+"");
}
AskNilesh
  • 67,701
  • 16
  • 123
  • 163
1

Slightly less elegant than Nilesh's answer, but as an alternative:

StringBuilder sb = new StringBuilder();

for (char c : strline.toCharArray()) {
    if ((sb.length() == 0 && "-".equals(c)) || Character.isDigit(c)) sb.append(c);
}

int amount = Integer.parseInt(sb.toString());

Edit Amended to allow for initial negative sign

Michael Dodd
  • 10,102
  • 12
  • 51
  • 64
  • I have another problem : My number is signed How can I get number sign (-or+)? – Azade Aug 03 '17 at 16:17
  • Updated my answer. It'll allow for a minus sign so long as no digits have yet been found. Ignoring + as lack of a minus will infer a positive value. – Michael Dodd Aug 03 '17 at 16:53
0

If you want all numeric char, you can use replaceALL in this way:

String numericString = strline.replaceAll("[^0-9]", "");

then use ParseInt.

Hope it helps.

Fusselchen
  • 382
  • 1
  • 4
  • 12
Andrea Ebano
  • 563
  • 1
  • 4
  • 16