Digits in a java string

Asked

Viewed 1,088 times

4

How do I find out how many digits a java string has ? For example, user entered with "exemplo123", the string has 3 digits. I’m using this function but it’s 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;
    }

5 answers

4


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

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);
    }
}
  • 1

    You can change 48 for '0' and 57 for '9'.

  • @Piovezan legal :D did not know this.

  • @Piovezan when you do if(asciiCode >= '0') .. the '0' is automatically converted to 48, would that be?

  • I don’t know what step Java does this, I think it’s in the lexical analysis. But the character that is between single quotes is converted to its Unicode value (if I’m not mistaken). You can also enter codes u0048 for example but I’m not used to using them.

  • 1

    https://www.cs.cornell.edu/andru/javaspec/3.doc.html

  • @rray, a Java character is a numeric type. So, '0' is considered the character 0, which has value 0x30

Show 1 more comment

4

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 is faster (Success #stdin #stdout 0.04s 4386816KB) than the toCharArray method (Success #stdin #stdout 0.06s 2841600KB)

3

String str = "123123asdasdas" ;
String aux = str;
aux = aux .replaceAll("\\D+","");
System.out.println("Quantidade de dígitos: " + aux .length());
  • I don’t want to delete, I want to know how many digits there are

  • Edited my dear, there was no need to give a negative.

  • I was looking for exactly this answer to give a +1! Your use of expressions is admirable

3

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 on 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 them.

1

public static int contaDigitos(String arg) {
    int nums = 0;
    for(char ch : arg.toCharArray()){
        if(Character.isDigit(ch)) nums++;
    }
    return nums;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.