Skip to content

Instantly share code, notes, and snippets.

@tuldok89
Created May 17, 2012 12:49
Show Gist options
  • Save tuldok89/2718690 to your computer and use it in GitHub Desktop.
Save tuldok89/2718690 to your computer and use it in GitHub Desktop.
Find a string within a string
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
string string1, string2;
int pos = -1;
vector<int> positions;
vector<int>::iterator itr;
cout << "Enter a string: \n";
getline(cin, string1);
cout << "\nEnter a string to find: \n";
getline(cin, string2);
for(;;)
{
pos = string1.find(string2, pos+1);
if (pos != string::npos)
positions.push_back(pos+1); // store position in list
else
break;
}
if (!positions.empty())
{
cout << "\nString found at position/s: ";
for(itr=positions.begin(); itr < positions.end(); itr++)
cout << *itr << " "; // print positions
}
else
cout << "\nString not found.";
cout << endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment