Saturday, 3 March 2018

Printing all occurrence (indexes) of a particular character in a string in c++

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main() {
string st="mississipi";
vector<char>s;
copy(st.begin(),st.end(),back_inserter(s)); // converting string to vector
s.push_back('\0');       //  converting string to vector
vector<char>::iterator it=s.begin();
int i=-1;
while(1){
    
it=find(s.begin()+i+1,s.end(),'s'); //once we find first 's' reduce the search range
if(it == s.end())
        break;
i=it-s.begin();  // storing index of the occurrence of 's' in string 
cout<<i;

}
return 0;



}

No comments:

Post a Comment