Advertisement
Advertisement


How to identify specific digits of an integer input in C?


Question

I need to get the number of digits containing the number 1. I know in java I can take the input as a String and use charAt, but I understand there is no implicit String function in C. How can I accomplish this?

2013/01/31
1
0
1/31/2013 7:54:00 PM


Homework?

You'd read it into a char* using the fread() function, and then store how many bytes were read in a separate variable. Then use a for loop to iterate through the buffer and count how many of each byte are present.

2008/09/15

If you have just the number, then you can do this:

 int val; //Input
 ...
 int ones = 0;
 while(val != 0) {
   ones += ((val % 10) == 1) ? 1 : 0;
   val /= 10;
 }

If you have a string (char*), the you'd do something like this:

while(*str != '\0') {
  if(*str++ == '1') {
    ones++;
  }
}

It's also worth noting that c does have a charAt function, in a way:

"java".charAt(i) == "c the language"[i];

By indexing into the char*, you can get the value you want, but you need to be careful, because there is no indexOutOfBounds exception. The program will crash if you go over the end of a string, or worse it may continue running, but have a messed up internal state.

2013/01/31

Try something like...

int digit = 0;
int value = 11031;

while(value > 0)
{
    digit = value % 10;
    /* Do something with digit... */
    value = value / 10;
}
2008/09/15

I see this as a basic understanding problem, which inevitably everyone goes through switching from one language to the next.

A good reference to go through to understand how string's work in C when you've started familiarity with java is look at how string.h works. Where as in java string's are an Object and built in, strings in C are just integer arrays.

There are a lot of tutorials out there, one that helped me when I was starting earlier in the year was http://www.physics.drexel.edu/students/courses/Comp_Phys/General/C_basics/ look at the string section.

Sometimes asking a question speeds up learning a lot faster than pouring through the text book for hours on end.

2008/09/16

int count_digit(int nr, int digit) {
    int count=0;
    while(nr>0) {
      if(nr%10==digit)
        count++;
      nr=nr/10;
    }
    return count;
}
2008/09/15

Source: https://stackoverflow.com/questions/66107
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]