tags:

views:

99

answers:

2

I am trying to create a small function that returns the number of spaces in a Char* variable using the C language.

Let's say I have this string :"hello hello hello". I want the function to return 2. This is the code I have so far:

int blankcounter(char* pline)
{                              
  int i=0;                  
  int counter = 0;            
  while (pline[i] != '\0')       
  {                               
    if (pline[i++] ==' ')
      counter++;
  }
  return counter;
}

the source that i am reading from is a txt file and 1 correction that i have to add is that the code that i posted indeed works but got 1 downside: if for example i want to read : "hello whats up "i want my function to be able to return 2 but it returns 3 because of the space that appears just after the wordup do u have any suggestion for me so it will return 2 ?

A: 

Question: Blank char counter in C?

Answer: Yes.

JustBoo
and yes the blank char is in c
Nadav Stern
+2  A: 

I suspect you would not want to count leading spaces too " hello whats up" should return 2 as well right?

I can propose 2 solutions. First is to trim all spaces before you start counting them http://stackoverflow.com/questions/122616/painless-way-to-trim-leading-trailing-whitespace-in-c.

The second is to adjust the start and end point of your loop to the first and last non-space characters and then perform the count:

int start=0;  
int end = strlen(pline);  
int i=0;  
while (pline[i++]==' ') start++;  
i=end-1;  
while (pline[i--]==' '&& i >= 0) end--;  
for (i=start; i<end; i++) { your count procedure} 
spbfox
the source that i am reading from is a txt file and 1 correction that i have to add is that the code that i posted indeed works but got 1 downside:if for example i want to read : `"hello whats up "`i want my function to be able to return 2 but it returns 3 because of the space that appears just after the word `up` do u have any suggestion for me so it will return 2 ?
Nadav Stern
I suspect you would not want to count leading spaces too " hello whats up" should return 2 as well right? I can propose 2 solutions. First is to trim all spaces before you start counting them <http://stackoverflow.com/questions/122616/painless-way-to-trim-leading-trailing-whitespace-in-c>. The second is to adjust the start and end point of your loop to the first and last non-space characters and then perform the count: int start=0;int end = strlen(pline); int i=0; while (pline[i++]==' ') start++; and the same way going down from the end of the string to adjust the "end".
spbfox