Created
May 17, 2012 12:49
-
-
Save tuldok89/2718690 to your computer and use it in GitHub Desktop.
Find a string within a string
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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