Thread: Number of words in a string problem

  1. #1
    Registered User
    Join Date
    Jun 2014
    Location
    Hubli, India
    Posts
    1

    Number of words in a string problem

    I know how to count number of words in a string but the problem with my code or what I am not able to do is, when I enter multiple ;; it shows as a word. The normal method is to do a count++ when a space is detected but what in case of multiple ;; or ]] or any special case. How do I make the complier to ignore special characters?
    My current code is

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


    void main()
    {
    char s[200];
    int count = 0, i;


    printf("enter the string\n");
    scanf("%[^\n]s", s);
    for (i = 0;s[i] != '\0';i++)
    {
    if (s[i] == ' '&& s[i+1]!= ' ')
    count++;
    }
    printf("number of words in given string are: %d\n", count + 1);
    }

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by MVK059
    The normal method is to do a count++ when a space is detected but what in case of multiple ;; or ]] or any special case. How do I make the complier to ignore special characters?
    Try writing a simple state machine. You have two states: you are either dealing with a word or you are dealing with a word separator. Check the current character. If it is a word character and you are dealing with a word separator, then you increment the count and change the state. Otherwise, you skip the current character, changing the state if necessary.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    You might also want to look up functions in the standard header <ctype.h>. There are various functions there for testing if a character is in various categories, such as alphabetic, uppercase, lowercase, punctuation, whitespace, printable.....
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.

  4. #4
    Registered User
    Join Date
    Jun 2014
    Posts
    1
    You can try the below code.
    insert
    Code:
    #include
    Code:
    <
    Code:
    stdio.h>
    
    #include<conio.h>
    int main()
    {
     int count_words=0,i;
     int count_char=0; 
     char str[20];
     printf("Enter string : ");
     gets(str);
     for(i=0; str[i]!=NULL; i++)
     { 
       count_char++;
       if(str[i]==' ')
          count_words++;
     }
     printf("\nNumber of characters in string : %d",count_char);
     printf("\nNumber of words in string : % d",count_words+1); 
    getch();
     return 0;
    }

    Please Visit us at:
    http://www.ati-erp.com

  5. #5
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,909
    @Elizabeth_Keen:
    Please don't post full solutions to people's homework problems. First off, it's against the forum guidelines and homework policy (which you were supposed to read and which you agreed to abide by as part of your membership). More importantly, however, is that it makes it harder for people to actually learn to program. Instead they end up simply learning how to copy-paste code. The problem solving skills that are necessary for programming are not developed.

    Also, please post your code as plain text next time (our forum will handle syntax highlighting and line numbering), and make sure it's properly indented so it is easy to read and follow the logic.

    This is all somewhat moot, however, since your program is broken. Things that are wrong:

    • conio.h is an ancient, outdated header that is not standard C, many people don't have it and including it only makes your code broken on their systems. The only function you use from conio.h is getch(), which is to wait for a keypress before exiting (also, you don't tell the user to press any key to exit, which you should do so they don't think your program is stuck). Prefer the standard function getchar(), which is part of stdio.h, to wait for a keypress.
    • You use gets. Gets is bad, read this link.
    • It does not handle strings with leading or trailing spaces correctly.
    • It does not handle multiple spaces between words correctly.
    • NULL is not quite the same as '\0'. NULL is a pointer with a value of 0 (though the internal representation for any given architecture may be different). '\0' is a character constant representing the null character and used to mark the end of strings, which also has a numeric value 0. When you are comparing characters looking for the end of string marker, prefer '\0' since it more clearly expresses what you are doing, and the type matches the type of object you are comparing (i.e. both are chars) instead of comparing a char (str[i]) to a pointer (like NULL).
    Last edited by anduril462; 06-11-2014 at 05:22 PM. Reason: added links

  6. #6
    Guest Sebastiani's Avatar
    Join Date
    Aug 2001
    Location
    Waterloo, Texas
    Posts
    5,708
    Quote Originally Posted by Elizabeth_Keen View Post
    You can try the below code.
    insert
    Code:
    #include
    Code:
    <
    Code:
    stdio.h>
    
    #include<conio.h>
    int main()
    {
     int count_words=0,i;
     int count_char=0; 
     char str[20];
     printf("Enter string : ");
     gets(str);
     for(i=0; str[i]!=NULL; i++)
     { 
       count_char++;
       if(str[i]==' ')
          count_words++;
     }
     printf("\nNumber of characters in string : %d",count_char);
     printf("\nNumber of words in string : % d",count_words+1); 
    getch();
     return 0;
    }

    Please Visit us at:
    http://www.ati-erp.com

    Yikes, one look at that code and I can tell you this: I will *never* seek out the services of ATI-ERP!
    Code:
    #include <cmath>
    #include <complex>
    bool euler_flip(bool value)
    {
        return std::pow
        (
            std::complex<float>(std::exp(1.0)), 
            std::complex<float>(0, 1) 
            * std::complex<float>(std::atan(1.0)
            *(1 << (value + 2)))
        ).real() < 0;
    }

  7. #7
    Registered User
    Join Date
    May 2014
    Posts
    12
    Quote Originally Posted by MVK059 View Post
    I know how to count number of words in a string but the problem with my code or what I am not able to do is, when I enter multiple ;; it shows as a word. The normal method is to do a count++ when a space is detected but what in case of multiple ;; or ]] or any special case. How do I make the complier to ignore special characters?
    Well, you have to decide what constitutes a word.
    Code:
    if (s[i] == ' '&& s[i+1]!= ' ')
                count++;
    According to your code here you are counting spaces between non space characters, not counting words. Again, what is a word?

    I suggest you look at the function strtok() if your assignment allows it. It's in the <string.h> header.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 3
    Last Post: 12-10-2012, 12:24 AM
  2. Replies: 3
    Last Post: 10-02-2012, 12:49 PM
  3. Replies: 7
    Last Post: 10-01-2010, 04:09 PM
  4. Replies: 5
    Last Post: 06-05-2010, 03:04 AM
  5. number of words in a string
    By jackhasf in forum C Programming
    Replies: 11
    Last Post: 12-26-2009, 03:37 PM

Tags for this Thread