Digits in a java string

5

How do I find out how many digits a String has in Java? For example, user entered with "example123", the string has 3 digits. I am using this function but it is not working:

private static int digitos(String text) {
        char[] digitos = new char[9];
        int digitosTotal = 0;
        for (int i = 0; i != 9; i++) {
            digitos[i] = (char) i;
        }
        for (int i = 0; i < digitos.length; i++) {
            if (text.indexOf(digitos[i]) != -1) {
                digitosTotal++;
            }
        }
        return digitosTotal;
    }
    
asked by anonymous 24.05.2017 / 00:49

5 answers

5

You can find out how many digits in the string can iterate through it, and compare the ascii code of each element if it is in the range of 48 and 57.

Example - ideone

Wikipedia - ascii table

import java.util.*;
import java.lang.*;
import java.io.*;

class Ideone
{
    public static void main (String[] args) throws java.lang.Exception
    {
        String text = "Digito123";

        char[] digitos = new char[9];
        int digitosTotal = 0;

        for(char caracter : text.toCharArray()){
            int asciiCode = (int)caracter;
            if(asciiCode >= 48 &&  asciiCode <= 57) digitosTotal++;
        }

        System.out.print(digitosTotal);
    }
}
    
24.05.2017 / 01:02
5

Using the isDigit method of the Character class example - ideone

import java.util.*;
import java.lang.*;
import java.io.*;

class Ideone
{
    public static void main (String[] args) throws java.lang.Exception
    {

        String text = "Digito123";

        int count = 0;
        for (int i = 0, len = text.length(); i < len; i++) {
          if (Character.isDigit(text.charAt(i))) {
           count++;
          }
        }

        System.out.print(count);

    }
}
  

The charAt method shows up faster (Success #stdin #stdout 0.04s 4386816KB) than the toCharArray method (Success #stdin #stdout 0.06s 2841600KB)

    
24.05.2017 / 02:10
4
String str = "123123asdasdas" ;
String aux = str;
aux = aux .replaceAll("\D+","");
System.out.println("Quantidade de dígitos: " + aux .length());
    
24.05.2017 / 00:58
4

You can use regular expression to count the number of digits and to extract them from the text, if necessary:

import java.util.*;
import java.util.regex.*;

class Main {

  public static void main(String[] args) {

    // Total de dígitos:
    int count = 0;

    // Lista de dígitos:
    List<Integer> digits = new ArrayList<Integer>();

    // Expressão regular para obter um dígito:
    Pattern p = Pattern.compile("\d");

    // Texto a ser analisado:
    Matcher m = p.matcher("exemplo123");

    // Conta quantos dígitos há no texto:
    while (m.find())
    {
      // Incrementa a quantidade de dígitos:
      count++;

      // Insere o dígito na lista:
      digits.add(new Integer(m.group()));
    }

    // Exibe o total:
    System.out.println(count);

    // Exibe a lista de dígitos:
    System.out.println(digits);

  }

}
  

See working at Ideone .

The output of the code is:

3
[1, 2, 3]

Where 3 indicates the number of digits and [1, 2, 3] the list of digits.

    
24.05.2017 / 01:05
1
public static int contaDigitos(String arg) {
    int nums = 0;
    for(char ch : arg.toCharArray()){
        if(Character.isDigit(ch)) nums++;
    }
    return nums;
}
    
24.05.2017 / 23:32