Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Function that counts the number of times a specific character appears in a string

  1. Mar 9, 2009 #1
    I have an assignment for my CS class.

    It is the following:

    *
    * complete the function:
    *
    * timesFound(string searchIn, char searchFor);
    *
    * The function should return the number of times the
    * character searchFor appears in the string searchIn.
    *
    */
    int timesFound(string searchIn, char searchFor)
    {
    }

    int main()
    {
    string textLine;
    char findThis, response = 'y';
    bool running = true;

    while (running)
    {
    cout << "Please enter a line of text: ";
    getline(cin, textLine);
    cout << "Please enter the character to search for: ";
    cin >> findThis;

    cout << "The search character was found " << timesFound(textLine, findThis) << " times.\n";

    cout << "Would you like to continue? (y/n) ";
    cin >> response;

    while (response != 'n' && response != 'y')
    {
    cout << "Would you like to continue? (y/n) ";
    cin >> response;
    }

    if (response == 'n')
    running = false;
    else
    cin.ignore();

    }

    }

    As always I know what the program is supposed to do, but I am lost on how to start. Any help is appreciated. Thank you
     
  2. jcsd
  3. Mar 10, 2009 #2
    Try putting your string into an array of chars and test each index. Let us see your attempt.
     
  4. Mar 10, 2009 #3
    Well, this isn't the homework forum, so I'm going to take whoever at his word and assume he just wants to know for his own curiosity. Maybe he's learning to program on his own... well, either way, I am going to treat him like an adult and just answer the guy's question.

    Alright, so the "string" class in C++ contains an overloaded operator for array-access, the brackets. []

    You can use this to check the value of individual characters in the string; so loop over the string's length, checking each character, and if it's equal to the target, increment the counter by one. For instance,

    int timesFound(string searchIn, char searchFor)
    {
    int result = 0;

    for(int i = 0; i < searchIn.length(); i++)
    {
    if(string == searchFor) result++;
    }

    return result;
    }
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook