开发者

Counting characters in C

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] != ' ') {
        ch开发者_运维技巧arcount ++;
    }
}

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 ++;
                }
        }


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)


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++;
}


Instead of using scanf, try fgets like so:

char input[256];
fgets(input, sizeof(input), stdin);

fgets will read an entire line from a file. As such, passing stdin as the file handle will make it read from standard input, which in most cases will be bound to the console. One thing to watch out for, though, is that the string you get from fgets might include the newline character. Rather than explicitly checking your strings for inequality with the space character (' '), I suggest using the isspace function from ctype.h, which will check for various forms of whitespace (including a regular space and newline).

Here is a complete, runnable example:

#include <stdio.h>
#include <ctype.h>

int count_nonspace(const char* str)
{
 int count = 0;
 while(*str)
 {
  if(!isspace(*str++))
   count++;
 }
 return count;
}

int main()
{
 char input[256];
 fgets(input, sizeof(input), stdin);
 printf("%d\n", count_nonspace(input));
}


Yes, there is a difference on input-scan with scanf:

    scanf("%s", z);
...
                if(z[m] != ' '){

scanf("%s"...) always breaks at space-character, therefore your if ever is true. Better you use fgets to read from stdin,

#define MAXINPUT 80
char line[MAXINPUT];
for(j=0; j<7; j++) {
  printf("Enter a string:\n");
  if( fgets( line, 80, stdin ) )
  {
    char *c=line;
    if( strchr(line,'\n') ) *strchr(line,'\n')=0;
    while( *c )
    {
      if( *c!=' ' )
        ++charcount;
      ++c;
    }
  }
}

Or if you want WHITE -spaces then take

#include <ctype.h>
...
if( !isspace(*c) )


this seems to work for me, its a simple 30 line code that is in a loop and can detect the letter of choice for the chosen string/sentence/word the user has inputted.

#include <stdio.h>  
#include <string.h>  
   
int main(){
 
  
    
while(true){

    char string[100]; 
    char letter[100];
    int count = 0;
    printf("Enter a word/sentence:\n");  
    scanf(" %[^\n]s",string); 
    printf("Enter a letter:\n");
    scanf(" %c",&letter); //when using scanf for a sentence/word or character, always include a space afterwards.
    //Counts each character except space  
    for(int i = 0; i < strlen(string); i++) {  
        if(string[i] == letter[0]){
         
            count++;  
        }
    }
      
    //Displays the total number of characters present in the given string  
    printf("Total number of characters in the string: %d\n", count);  
    printf("%s\n",string);
}

    return 0;  
}  
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜