Taz
Taz

Reputation: 23

Counting a String within a string

I'm told to ask the user for a string ( a sentence). Then the user is asked to input another string to search in string 1 (the sentence). The program has to count the number of times the second string shows up in the first string. I'm not getting any errors but it's is not counting the letters. This is the result i get:

Enter a sentence:i love to eat soup

Enter string to search: ou

There are 0 of the string ou in the first string you provided.

Can someone please tell me what i'm doing wrong? I'm a beginner at c++ so i'm having some trouble understanding.

#include <iostream>
#include <string>
using namespace std;

int  main() {

        string sentence;
        string search;
        int count = 0;

        cout<<"Enter a sentence:";
        getline (cin, sentence);
        cout<<"Enter string to search:";
        getline (cin, search);

        cout << "There are " << count << " of the string " << search << " in the first string you provided." <<"\n";

        for (int i=0; i < sentence.size(); ++i)
        {
                if (sentence == search)

                count++;
        }

        return count;


}

Upvotes: 0

Views: 177

Answers (5)

Andy Prowl
Andy Prowl

Reputation: 126412

You should modify your loop so that it really searches for substrings and count their occurrences:

string::size_type pos = sentence.find(search);
while (pos != string::npos)
{
    pos = sentence.find(search, pos + search.size());
    count++;
}

Also, you most likely want to move this line after the point where you actually compute the value of count:

cout << "There are " << count << ...

Otherwise, it will obviously output the value to which count was initialized originally (i.e. 0).

Upvotes: 0

MSN
MSN

Reputation: 54554

Two issues:

  1. You print count before you calculate it.
  2. You are not actually searching for a substring. You should look at the documentation for std::string to find an appropriate way to search for substrings. However, you are on the right track.

Upvotes: 2

Junfei Wang
Junfei Wang

Reputation: 578

looks like you should put the cout statement in the end of this method. Because in your code, count is always 0 when you output it

Upvotes: 0

jpporterVA
jpporterVA

Reputation: 649

You have your cout print line after the loop where you search for the string and set the count. Move it below that loop.

Upvotes: 0

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385108

Well, you're trying to output the results before calculating them.

Also, == is for exact matches, not substring searches.

Upvotes: 0

Related Questions