Home > Net >  How do I make the strlen() function not count spaces?
How do I make the strlen() function not count spaces?

Time:09-15

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

int main(void) {
    char string[1024];
    int len = 0;
    int i = 0;
    while (fgets(string, sizeof(string), stdin) != 0);
    len = strlen(string) - 1;
    if (len % 2 == 0) {
    printf("%s", string);
    }
}

The aim of this code is to print out inputs that have an even number of characters and omit anything else (will not print it). The program works when there is no space in the string however once I place a space it counts it as the length which I'm trying to stop. How do I make this program omit spaces when counting the length of the string?

CodePudding user response:

How do I make the strlen() function not count spaces?

The standard function strlen() simple does not do that. Easy to code a new function that does.

#include <ctype.h>
#include <stddef.h>

size_t spaceless_strlen(const char *s) {
  size_t len = 0;
  const unsigned char *us = (const unsigned char *) s;
  while (*us) {
    if (*us != ' ') len  ;
    // Or if not counting white-spaces
    if (!isspace(*us)) len  ;
    us  ;
  }
  return len;
}

Best to pass unsigned char values to is...() functions so a unsigned char * pointer was used.

CodePudding user response:

Regarding how you can achieve counting characters that are not spaces, you can try this.

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

int main(void) {
    char string[1024];
    int len;
    int count=0;
    int i;
    while (fgets(string, sizeof(string), stdin) != 0){
    len = strlen(string) ;
    for (i=0; i<len;i  )
    {
        if (string[i]!=' ')
            count  ;
    }
    if (count % 2 == 0) 
    {
        printf("%s", string);
    }
}
    return 0;
}

Note: In my opinion, this isn't the most optimal way to achieve so but I tried to keep it based on your code and logic!

This seems better :

#include <stdio.h>
#include <stdlib.h>
int main()
{
    char str[1024];
    int i=0,count=0;
    printf("Enter a String\n");
    gets(str);
    while(str[i]!='\0')
    {
        if(str[i]!=' ')
        {
            count  ;
        }
        i  ;
    }
  if(count% 2 ==0)
  {
   printf("%s ",str,);
  }
  return 0;
}
  •  Tags:  
  • c
  • Related