Thread: HELP in STRING. counting words

  1. #1
    Registered User
    Join Date
    Nov 2011
    Posts
    19

    HELP in STRING. counting words

    help..my c program is counting "SPACE" i dont want to count it as "Word" can anybody help??

    here's my code:

    Code:
    #include<stdio.h>
    #include<ctype.h>
    #include<string.h>
    
    int main(){
        
    char str[1000], p;
    int i, count=1;
    
    printf("Enter a string: ");
    gets(str);
    
        for (i=0; str[i]!='\0'; i++){
            if(str[i]==' '){
                count++;
            }
        }
    
    
    printf("There are %d words\n\n",count);
    
        for (i=0; str[i]!='\0'; i++){
            if(str[i]==' '){
                printf("\n");
            } 
            else{
                printf("%c", str[i]);
            }
        }
        
    printf("\n");
    
    return 0;
    
    
    }

  2. #2
    Registered User camel-man's Avatar
    Join Date
    Jan 2011
    Location
    Under the moon
    Posts
    693
    What is the problem?

  3. #3
    Registered User
    Join Date
    Nov 2011
    Posts
    19
    Quote Originally Posted by camel-man View Post
    What is the problem?
    problem is, when i type a word/ sentence with more space inside, it count the space as word.

    example:

    red(space)(space)is(space)color.

    there are 4 words:
    red

    is
    color


    but it is only 3 words...help pls...

  4. #4
    Registered User camel-man's Avatar
    Join Date
    Jan 2011
    Location
    Under the moon
    Posts
    693
    if next character is not space

    ex.

    Code:
        for (i=0; str[i]!='\0'; i++){
                    if(str[i]==' '&& str[i+1]!=' '){
                       count++;
                        }
                     }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Counting words in an string
    By Imara in forum C Programming
    Replies: 2
    Last Post: 12-17-2011, 08:53 AM
  2. Replies: 5
    Last Post: 06-05-2010, 03:04 AM
  3. Counting the words in a string C++
    By mblue in forum C++ Programming
    Replies: 8
    Last Post: 03-30-2009, 01:39 PM
  4. help with counting words
    By geo_c in forum C Programming
    Replies: 7
    Last Post: 08-23-2004, 06:53 AM
  5. counting words in string
    By Unregistered in forum C Programming
    Replies: 9
    Last Post: 05-30-2002, 04:10 AM