Thread: Help with searching for a char in a string

  1. #1
    Registered User
    Join Date
    Oct 2006
    Posts
    13

    Help with searching for a char in a string

    I am working a coding problem in my book about using the strchr() function to search for a char in a string. Now, I can obviously do that, but the problem I am having is it wants me to now have the program count how many times that certain characters appears in the string. The problem is that since strchr goes until the first occurence and stops; I am not sure as to what to do next... I was thinking a for loop, but I can't come up with a correct loop. Here is my code:
    Code:
    #include <stdio.h>
    #include <string.h>
    
    void main()
    {
    	const char *string = "The bad man waned throughout the day";
    	char character = 'a';
    	int count = 0;
    
    	if(strchr(string, character) != NULL)
    		count++;
    
    	printf("Character %c appears %d times\n", character, count);
    }
    Now, would a for loop be put to good use here or am I thinking off?

    Sorry I didn't add this in the main post, but I am searching for the character a as an example so I can get it to work.

  2. #2
    {Jaxom,Imriel,Liam}'s Dad Kennedy's Avatar
    Join Date
    Aug 2006
    Location
    Alabama
    Posts
    1,065
    In place of just testing for NULL, grab that location with a char *, then, inc and let that be the string you search.

  3. #3
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    Okay, since strchr looks for the first matching character in the string, your best bet is to use a loop. However, make sure you move past the match or you'll have an infinite loop. You can use the pointer that strchr gives you as the argument for the next call. It's kind of trippy, but it works.
    Code:
    while ( ( string = strchr ( string, character ) ) != NULL ) {
      ++count;
      ++string; // Jump past the matching character
    }
    >void main()
    main returns int.
    My best code is written with the delete key.

  4. #4
    Registered User
    Join Date
    Oct 2006
    Posts
    13
    Ah, thank you.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. char Handling, probably typical newbie stuff
    By Neolyth in forum C Programming
    Replies: 16
    Last Post: 06-21-2009, 04:05 AM
  2. Replies: 8
    Last Post: 04-25-2008, 02:45 PM
  3. newbie needs help with code
    By compudude86 in forum C Programming
    Replies: 6
    Last Post: 07-23-2006, 08:54 PM
  4. code condensing
    By bcianfrocca in forum C++ Programming
    Replies: 4
    Last Post: 09-07-2005, 09:22 AM
  5. String Class Operations
    By Aidman in forum C++ Programming
    Replies: 10
    Last Post: 04-06-2003, 02:29 PM