print a string after a character in c 2b 2b

Solutions on MaxInterview for print a string after a character in c 2b 2b by the best coders in the world

showing results for - "print a string after a character in c 2b 2b"
Merlin
03 Aug 2016
1/*
2This is a simple algorithm implemented using arrays!
3This can also be used when you're asked to find a replacement to the string.find() method
4*/
5
6#include <iostream>
7#include <vector>
8using namespace std;
9
10int main() {
11    string str;
12    cout << "Enter string: ";
13    cin >> str;
14
15    vector<int> indexes; // stores the positions of the character we're searching for in the string
16    vector<string> result; // stores the returned substrings
17	
18    int count = 0, targetIndex = 0; // count stores the number of times the target character repeats in the string
19    // targetIndex stores the present index of the character
20  	for (int i = 0; i < str.length(); i++) { //  a raw for loop over the length of the string
21        if (str[i] == 'i' || str[i] == 'I') { // the character we're searching for is 'I' and 'i'
22            count++; // if 'i' or 'I' is in the string, increment the count varaible
23            targetIndex = i; // initialize the targetIndex variable with the index at which the character 'i' or 'I' is found
24            indexes.push_back(targetIndex); // with every loop/ iteration, keep pushing the indexes back to the array
25        }
26    }
27
28    string temp = ""; // a temperary string used later
29
30    for (int j = 0; j < indexes.size(); j++) { // looping over the indexes array
31        temp = str.substr(indexes[j] + 1, str.length()); // simply implementing the substring method => adding a starting index, and an ending index which is the length of the rest of the substring
32        result.push_back(temp); // pushing back all the returned substring to the result array
33    }
34
35    for (auto item : result) { // using a range based for loop to print the elements of the array
36        cout << item << "\n";
37    }
38  return 0; // end of the program!
39}