Nadav
Nadav

Reputation: 2717

Blank char counter in C

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 ?

Upvotes: 0

Views: 324

Answers (2)

spbfox
spbfox

Reputation: 949

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 How do I trim leading/trailing whitespace in a standard way?.

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} 

Upvotes: 2

JustBoo
JustBoo

Reputation: 1741

Question: Blank char counter in C?

Answer: Yes.

Upvotes: 0

Related Questions