Home > Software design >  Find Length of string without counting spaces
Find Length of string without counting spaces

Time:12-10

I'm making program that finds length of string entered by user. Everything is working but program also counts spaces. So, how to find length of string without counting spaces?

CodePudding user response:

  1. Use the correct types for sizes
  2. *(p x) === p[x] - where p is a pointer and x has integral type. Your both function are exactly the same.
  3. Use names that have some meaning string_array is not too informative and definitely does not indicate that it is returning the length of the string without spaces.
  4. do not use gets functions as it is very dangerous. Use functions that limit the number of characters placed in the string. For example fgets
size_t strlenNoSpaces(const char * restrict c)
{
    size_t length = 0;
    for(; *c; c  )
    {
        if(*c != ' ') length  ;
    }
    return length;
}

int main()
{
    char string[30];
    size_t length, i;

    printf("Enter string: ");
    fgets(string, 29, stdin);

    length = strlen(string);
    printf("\nLength of string using strlen.\n");
    printf("Length of string %zu.\n", length);

    length = strlenNoSpaces(string);
    printf("\nLength of string not counting the spaces.\n");
    printf("Length of string %zu.\n", length);

    return 0;
}
  • Related