Answers for "print a string after a character in c++"

C++
1

print a string after a character in c++

/*
This is a simple algorithm implemented using arrays!
This can also be used when you're asked to find a replacement to the string.find() method
*/

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

int main() {
    string str;
    cout << "Enter string: ";
    cin >> str;

    vector<int> indexes; // stores the positions of the character we're searching for in the string
    vector<string> result; // stores the returned substrings
	
    int count = 0, targetIndex = 0; // count stores the number of times the target character repeats in the string
    // targetIndex stores the present index of the character
  	for (int i = 0; i < str.length(); i++) { //  a raw for loop over the length of the string
        if (str[i] == 'i' || str[i] == 'I') { // the character we're searching for is 'I' and 'i'
            count++; // if 'i' or 'I' is in the string, increment the count varaible
            targetIndex = i; // initialize the targetIndex variable with the index at which the character 'i' or 'I' is found
            indexes.push_back(targetIndex); // with every loop/ iteration, keep pushing the indexes back to the array
        }
    }

    string temp = ""; // a temperary string used later

    for (int j = 0; j < indexes.size(); j++) { // looping over the indexes array
        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
        result.push_back(temp); // pushing back all the returned substring to the result array
    }

    for (auto item : result) { // using a range based for loop to print the elements of the array
        cout << item << "\n";
    }
  return 0; // end of the program!
}
Posted by: Guest on June-21-2021

Code answers related to "print a string after a character in c++"

Browse Popular Code Answers by Language