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:
- Use the correct types for sizes
*(p x)
===p[x]
- wherep
is a pointer andx
has integral type. Your both function are exactly the same.- 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. - do not use
gets
functions as it is very dangerous. Use functions that limit the number of characters placed in the string. For examplefgets
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;
}