Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Counting characters in C

Tags:

c

count

character

I'm trying to write a program that counts all the characters in a string. I originally had it, but then realized I can't count spaces. I can't see why this does not work.

for(m=0; z[m] != 0; m++) {
    if(z[m] != ' ') {
        charcount ++;
    }
}

Any assistance appreciated.

Edit* Does it make a difference if the input(strings) are being scanned in like this? And yes, everything is initialized. I've tried printing what z[m] evaluates too and it isn't the actual value of the string at "m", I think this is the problem.

for(j=0; j<7; j++){
    printf("Enter a string:\n");
    scanf("%s", z);
        for(m=0; z[m] != 0; m++){
                if(z[m] != ' '){
                charcount ++;
                }
        }
like image 745
James Avatar asked Sep 19 '10 12:09

James


2 Answers

You need to initialize charcount. Other than that, it should work, provided that z is a zero-terminated array of characters and m is an int or similar. I would probably write just z[m] rather than z[m] != 0 (since !0 = true and 0 = false), but both work. There are more efficient ways of doing it (although these days I bet a compiler will handle converting this into a pointer-based loop for you).

Here's a complete, correct example with minimal edits:

const char * z = "testing one two three";
int m;
int charcount;

charcount = 0;
for(m=0; z[m]; m++) {
    if(z[m] != ' ') {
        charcount ++;
    }
}

If you're using a String class of some kind rather than an old-fashioned C null-terminated array, you'll want to look at that class for how to loop through it.

All of the above also assumes you're dealing with ASCII strings. If you're dealing with UTF-encoded strings, you have to handle multi-byte characters.


Re your edit: It makes a big difference: scanf will stop on the first blank (I'd forgotten that). It might make an even bigger difference than that, though, if you're not declaring z correctly. (I'd also recommend using a field width when using scanf for reading strings [or avoiding scanf entirely]; otherwise, you have no control over the number of chars it will try to store, and so in theory, no buffer will ever be big enough to avoid an overflow. More here: http://www.crasseux.com/books/ctutorial/String-overflows-with-scanf.html)

like image 111
T.J. Crowder Avatar answered Sep 28 '22 18:09

T.J. Crowder


You can use strlen()

I'd suggest using a while loop, and to use more meaningful variable names

m = textIndex 
z = text

Something like this would work

while (text[textIndex] != 0x00)
{
  textIndex++;
}
like image 41
Anonymous Avatar answered Sep 28 '22 17:09

Anonymous