1

basically, Ive been asked to write a program that checks how many times a number is apparent in a string and print it out. This is what i have

    BufferedReader input = new BufferedReader (new InputStreamReader (System.in));
    System.out.println("Please enter your string");
    String s = input.readLine();
    /*System.out.println("Please enter the chracter you are looking for");
    char c = (char)input.read();*/
    char one = '1';
    char two = '2';
    char three = '3';
    char four = '4';
    char five = '5';
    char six = '6';
    char seven = '7';
    char eight = '8';
    char nine = '9';
    char zero= '0';
int counter = 0;
for( int i=0; i<s.length(); i++ ) {
    if( s.charAt(i) == one || s.charAt(i) == two || s.charAt(i) == three || s.charAt(i) == four || 
 s.charAt(i) == five || s.charAt(i) == six || s.charAt(i) == seven 
 || s.charAt(i) == eight || s.charAt(i) == nine || s.charAt(i) == zero ) {
        counter++;


    } 


}

is there a faster, better way to do this? I tried another way but for this error

Error: The operator || is undefined for the argument type(s) boolean, char
Sean
  • 60,939
  • 11
  • 97
  • 136
james
  • 55
  • 3

4 Answers4

0

Instead of declaring digits by yourself in the code, you can take a look at Character.isDigit() method in Java. This will make the code much cleaner. There's no other faster way of doing this.

If you want to count occurrence of each digit, one simple way to do that would be to use Java Maps. You can read basic tutorial about Maps from here.

raghav
  • 1
  • 2
0

this works in c#

foreach (char c in str)
    {
        if (c >= '0' && c <= '9')
            counter++;
    }
Marian Nasry
  • 821
  • 9
  • 22
0

You can use the decimal value of the character (as defined in the ASCII table)

String s = "abc123def456";
int cpt = 0;
for (int i = 0; i < s.length(); i++) {
    if (s.charAt(i) >= '0' && s.charAt(i) <= '9') {
        cpt++;
    }
}
System.out.println(cpt); // 6

You can also use the Character::isDigit method

if (Character.isDigit(s.charAt(i))) {
    cpt++;
}

EDIT :

If you are using Java 8+ you can turn the String in an stream of characters, apply a filter to keep the digits, and then count the number of elements in it.

long nbDigits = s.chars()
    .filter(Character::isDigit) // If the character is a digit (= the isDigit() method returns true) it's kept in the stream
    .count();
System.out.println(nbDigits); // 6
Junior Dussouillez
  • 2,327
  • 3
  • 30
  • 39
0

is there a faster, better way to do this

Your approach is absolute correct and almost maximum fast!. You could make it mo readable.

I think that general algorithm is the same for all languages with O(n):

  1. Loop the array and increment counter when find a number character.

Your approach is absolute correct and almost maximum fast!. (note: I really think that speed between two comparisons and nine is very-very small and we should not care about it) All you can do is just write it with as less lines of code as possible. You can do following corrections:

  1. char is integer in JVM and ASCII code for 0-9 is 0x30-0x39, so you can move from == to ch >= '0' && ch <= '9'.
  2. Character class contains special method to check it: Character.isDigit(ch).
  3. For java 8 you can use Streams instead of manual for...each.

Not using streams (plain old java) I think this approach provides maximum speed and lees memory objects

public int countDigits(String str) {
    int count = 0;

    for(int i = 0; i < str.length(); i++)
        if(Character.isDigit(str.charAt(i)))
            count++;

    return count;
}

Using streams (from java 8). Looks good, works a little bit slower that previous example, and creates some additional objects in memory.

public int countDigits(String str) {
    // could be a little bit slower, because additional objects are created inside
    return (int)str.chars().filter(Character::isDigit).count();
}

P.S. If you want to show your skill, plain old java variant is more preferable. In working code, both variant are equal.

P.P.S. actually String.toCharArray() or str.chars() are look more elegant and even a little bit less performed that str.charAr(int), because they create additional objects in memory, but str.charAr(int) works directly with internal arrays. But I did not faced with problem with any approaches in real application.

Oleg Cherednik
  • 17,377
  • 4
  • 21
  • 35
  • 2
    Your first claim is wrong. The OPs code calls charAt(i) ten times for each i. If you consider that to be "maximum fast" then you and me have a very different few what these two words mean. – GhostCat Sep 28 '17 at 13:36
  • @GhostCat +1. Agree with you. This is not absolute correct. I have modified my notes. – Oleg Cherednik Sep 28 '17 at 13:38