Question

I wanna count the length of the string (including spaces) with the function strlen() and the length of the string without the spaces. The former works, but I have problems with the latter.

Example:

Hello User//including spaces:10 letters//without spaces:9

When I enter a word without spaces the program always count:100, when with 1 space: I get 99 and so on.

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

#define N 100

int main()
{
    int counter1 = 0, i;
    char string1[N] = {0};
    {
        gets(string1);
        printf("\nYour Text:\n%s",string1);
        printf("\nLength of String:%i Letters(with spaces)", strlen(string1));
        for(i=0; i<N; i++)
        {
            if(string1[i] != ' ' && string1[i] != '0')
                counter1++;
        }
        printf("Number of Letters(without spaces): %i",counter1);
    }
    return 0;
}
Was it helpful?

Solution 3

while(str[i]!='\0')
 {
     if(str[i]!=' ')
     {
         count++;
     }
     i++;
 }

this loop works or chnage your for loop to

for(i=0; i<strlen(string1); i++)
        {
            if(string1[i] != ' ' && string1[i] != '0')
                counter1++;
        }

since you used

for(i=0; i<N; i++)

where N=100 and c will not check for out of bound access therefore the loop continues till i=100 this resulted in count=100-number of spaces.

OTHER TIPS

You have not considered that the string terminate with '\n'. Your code will run from 0 till 100 so you will always get 100 as result. You could change your code with something like this:

i=0;
while(string1[i]!='\n' && string1[i]!='\0')
{
  if(string1[i]!=' ') {
      counter1++;
  }

  i++;
}

Please take note that in C the default string therminator character is '\0' and not 0

if you want a C++ answer (you did add C++ tag), then you can do :

std::string tmp(str);
int cpt = std::count_if(tmp.begin(),tmp.end(),[](char c){return c != ' ';});

In C#:

int numberOfChars = yourString != null ? yourString.Replace(" ", "").Count() : 0;

Have a nice day,

Alberto

You must check for NULL (string1[i] == 0) character. Once you encounter NULL, break from the for loop.

my approach would be:

int len = strlen(string1);
int lenWithoutSpace = len;
for(int i=0; i<len; ++len){
  if(string1[i]==' '){
    lenWithoutSpace--;
  }
}

try the following code:

int main()
{
int counter1=0,i;
char string1[N]={0};
{   
gets(string1);
printf("\nYour Text:\n%s",string1);
printf("\nLength of String:%i Letters(with spacebar)",strlen(string1));
 for(i=0;i<strlen(string1);i++)
{
  if(string1[i]!=' '&&string1[i]!='0')
    counter1++;
}    
printf("Number of Letters(without spacebar): %i",counter1);
}
return 0;
}

Your loop adds up to 100, excluding the space and '0', which i believe you want it to be '\0'. Change the loop to 0 to strlen(string1) and the if condition, and it should work fine. Although there can be better ways.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top