简体   繁体   中英

how to count the number of characters and ignore space in C

Following is my code, when I enter "carol chen", I expect it will print out 9 characters, but it print out 10.

The name you enter is: carol chen

The number of characters in the user's name is 10

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(){

char *name;
int i;
int n = 0;

name= (char *)calloc(80, sizeof(char));

if(name == NULL) {

    printf("\nOut of memory!\n");
    return 1;
}
else {

    printf("The name you enter is: ");
    scanf("%79[0-9a-zA-Z ]", name);

    for(i=0; i<80; i++){

        if(name[i] != 0){

            n += 1;
        }
    }

    printf("\nThe number of characters in the user's name is %d\n", n);

}

free(name);

}

Just don't count the spaces by adding an and clause that excludes spaces inside your if condition:

Try this:

if (name[i] != 0 && name[i] != ' ')
{
    n += 1;
}

Here is a more efficient version

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
        char *name;
        int i;
        int n = 0;

        name= (char *)calloc(80, sizeof(char));

        if(name == NULL) {
            printf("\nOut of memory!\n");
            return 1;
        }
        else {
            printf("The name you enter is: ");
            scanf("%79[0-9a-zA-Z ]", name);
        }

        i = 0;
        while ( (i < 80) && name[i])  {
            if(name[i] != ' ') {
                n += 1;
            }
            i++;
        }
        printf("\nThe number of characters in the user's name is %d\n", n);

        free(name);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM