Search code examples
ccountingstrlen

How to count number characters of strings without using strlen


I have the task to count the number of letters in random words until "End" is entered. I'm not allowed to use the strlen(); function. That's my solution so far:

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

int stringLength(char string[]){
    unsigned int length = sizeof(*string) / sizeof(char);
    return length;
}

int main(){
    char input[40];
    
    while (strcmp(input, "End") != 0) {
        printf("Please enter characters.\n");
        scanf("%s", &input[0]);
        while (getchar() != '\n');
        printf("You've entered the following %s. Your input has a length of %d characters.\n", input, stringLength(input));
    }
}

The stringLength value isn't correct. What am I doing wrong?


Solution

  • The %n specifier could also be used to capture the number of characters.
    Using %39s will prevent writing too many characters into the array input[40].

    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    
    int main( void)
    {
        char input[40] = {'\0'};
        int count = 0;
    
        do {
            printf("Please enter characters or End to quit.\n");
            scanf("%39s%n", input, &count);
            while (getchar() != '\n');
            printf("You've entered the following %s. Your input has a length of %d characters.\n", input, count);
        } while (strcmp(input, "End") != 0);
    
        return 0;
    }
    

    EDIT to correct flaw pointed out by @chux.
    using " %n to record leading space and %n" record total characters this should record the number of leading whitespace and the total characters parsed.

    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    
    int main( int argc, char *argv[])
    {
        char input[40] = {'\0'};
        int count = 0;
        int leading = 0;
    
        do {
            printf("Please enter characters. Enter End to quit.\n");
            if ( ( scanf(" %n%39s%n", &leading, input, &count)) != 1) {
                break;
            }
            while (getchar() != '\n');
            printf("You've entered %s, with a length of %d characters.\n", input, count - leading);
        } while (strcmp(input, "End") != 0);
    
        return 0;
    }
    

    EDIT stringLength() function to return length

    int stringLength(char string[]){
        unsigned int length = 0;
        while ( string[length]) {// true until string[length] is '\0'
            length++;
        }
        return length;
    }