Strings homework trouble
Mar 12, 2013 at 3:05pm UTC
I need to create a program that will ask for a paragraph, then a string to search for in that paragraph. The output will be a list of each spot where the string can be found within the paragraph. This is what I've come up with, though it's not working as intended yet. Any suggestions?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
#include <iostream>
#include <string>
using namespace std;
int main()
{
string paragraph;
string searchPhrase;
int startPoint = 0;
int tempStartPoint = 0;
cout << "Enter your paragrph:\n\n" ;
cin >> paragraph;
cout << "Enter string to search for:\n" ;
cin >> searchPhrase;
do
{
if (paragraph.find(searchPhrase,startPoint) != string::npos)
{
cout << "\nI found " << searchPhrase << " at location " << paragraph.find(searchPhrase,startPoint) << endl;
tempStartPoint = paragraph.find(searchPhrase,startPoint);
startPoint = tempStartPoint;
}
} while (paragraph.find(searchPhrase,startPoint) != string::npos);
cout << "\n" << searchPhrase << " no more found." ;
int pause;
cin >> pause;
return 0;
}
Mar 12, 2013 at 3:17pm UTC
This code snip
1 2 3 4 5 6 7 8 9
do
{
if (paragraph.find(searchPhrase,startPoint) != string::npos)
{
cout << "\nI found " << searchPhrase << " at location " << paragraph.find(searchPhrase,startPoint) << endl;
tempStartPoint = paragraph.find(searchPhrase,startPoint);
startPoint = tempStartPoint;
}
} while (paragraph.find(searchPhrase,startPoint) != string::npos);Y
can be rewritten simpler
1 2 3 4 5 6
for ( std::string::size_type pos = paragraph.find( searchPhrase, 0 );
pos != std::string::npos;
pos = paragraph.find( searchPhrase, pos + searchPhrase.size() ) )
{
cout << "\nI found " << searchPhrase << " at location " << pos << endl;
}
Last edited on Mar 12, 2013 at 3:18pm UTC
Topic archived. No new replies allowed.