I have an array of 5 words. I find the letters I need in these words and change them. And the second task is to take the last 2 letters from each word and put them into a substring. Those. we take the word maybe and we need to take the letters be from it, then bring them to the screen.

#include <vector> #include <algorithm> using namespace std; void myfunction(string& i) { for (auto idx = i.find("ab"); idx != string::npos; idx = i.find("ab")) { i.replace(idx, 2, "ccc"); } } int main() { vector<string> v; v.push_back("soon able brabus strong crab"); ostream_iterator<string> printit(cout, " "); cout << "Before replacing" << endl; copy(v.begin(), v.end(), printit); for_each(v.begin(), v.end(), myfunction); cout << endl; cout << "After replacing" << endl; copy(v.begin(), v.end(), printit); cout << endl; system("pause"); return 0; } 

I found how easy it is to remove words with certain letters, found how to search for words with non-recurring letters. But how to find the 2nd last letters in the words array, and then display them on the screen, I could not.

  • I thought you had a problem with the string, not with the vectors. Added your answer, look. - AivanF.

2 answers 2

If you need to pull out of the array of words, then so probably:

 std::vector<std::string> temp; for(auto& it:v){ temp.push_back(it.substr(it.size() - 2, 2)); } 

Then output this array of strings "with the last 2 letters":

 for(auto& it:temp){ cout << it<< "\n";//printf_s("%s", it.c_str()) } 
  • Now it displays only the last 2 characters of the last word. What if you put a comma, and the landmark was on them? Perhaps then he will print all the last 2 letters of the words. But how to do that? - nico1st

string::substr to help you:

 string source = "maybe"; string result = source.substr(source.size() - 2, 2); cout << result << "\n"; // output: be 

UPD. With vector:

 // вектор исходных слов vector<string> words; words.push_back("maybe"); words.push_back("go"); words.push_back("to be"); words.push_back("banana"); // вектор для окончаний vector<string> ends; // добавление окончаний слов for (auto it = words.begin(); it != words.end(); it++) { string &s = *it; // можно добавить ещё проверку на достаточную длину слова ends.push_back(s.substr(s.size() - 2, 2)); } // вывод for (auto it = ends.begin(); it != ends.end(); it++) { cout << *it << " "; } cout << "\n"; // output: be go be na