Thread: How to count number of spaces, certain letters, etc. in strings?

  1. #1
    Registered User
    Join Date
    Oct 2011
    Posts
    32

    How to count number of spaces, certain letters, etc. in strings?

    Hello, I was wondering if anyone knew how to get a program to count the number of certain elements in a string.

    Here's an example code I made. How would I determine the number of spaces in line1 and the number of punctuation marks in line2 that would return that back to the main?

    Code:
    #include <stdio.h>
    #include <string.h>
    
    
    int spaceCount(char line1[]);
    int locatePunctuation(char line2[]);
    
    
    void main()
    {
                char line1[] = "I like chocolate chip cookies."
                char line2[] = "Hi. My name is DW. How are you today?"
                printf(spaceCount(line1));
                printf(locatePunctuation(line2));
    
    
    }
    
    
    int spaceCount (char line1[])
    {
    
    
    }
    
    
    int locatePunctuation(char line2[])
    {
    
    
    }
    I'm guessing for punctuation I would need something like (correct me if I'm wrong):

    Code:
    int count = 0, i;
    for(i = 0; i < strlen(line);i++) // counts # of punctuation marks in the string
    {
              if(ispunct(line[i] )) { count++; }
    }
    printf(“%d \n”, count);
    ??

    Not sure about spaces though.

    Thanks!

  2. #2
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Look up the following functions in your C library documentation...
    (If you don't have it.. get it.)

    ispunct()
    isspace()
    isalpha()
    isdigit()

  3. #3
    Registered User
    Join Date
    Oct 2011
    Posts
    32
    Ah that helped. Thank you very much!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Count number of letters...
    By sponi in forum C Programming
    Replies: 24
    Last Post: 09-14-2011, 10:30 PM
  2. Replies: 5
    Last Post: 06-05-2010, 03:04 AM
  3. Count Number of Letters in a Word
    By quiksand in forum C Programming
    Replies: 10
    Last Post: 05-14-2010, 11:44 PM
  4. Count number of letters and numbers in a file
    By jtullo in forum C Programming
    Replies: 2
    Last Post: 04-21-2008, 01:33 AM
  5. Count the letters of a string.
    By blackjs in forum C++ Programming
    Replies: 1
    Last Post: 10-17-2001, 10:15 PM