OOP_zadanie8/Main.cpp

68 lines
1.8 KiB
C++

#pragma once
#include <string>
#include <vector>
#include <iostream>
#include <algorithm>
void tokenize(std::string str, std::vector<std::string>& token_v);
bool isPalindrome(std::string str);
std::string replaceStr(std::string str, const std::string& from, const std::string& to);
int main() {
std::string str = "Hi how are you and WOW and abba";
std::vector<std::string> str_vector;
std::vector<std::string> str_vector_pal;
int palindromeCounter = 0;
std::cout << "Source string: " << str << "\n";
std::cout << "Edited string: " << replaceStr(str, "and", ",and") << "\n\n";
tokenize(str, str_vector);
for (std::string& str: str_vector)
{
if (isPalindrome(str))
{
palindromeCounter += 1;
str_vector_pal.push_back(str);
}
}
std::cout << "Palindrome Counter = " << palindromeCounter << "; ";
for (std::string& str: str_vector_pal)
{
std::cout << str << ", ";
}
std::cout << "\n";
system("pause");
return 0;
};
bool isPalindrome(std::string str) {
std::string tmp = str;
std::reverse(tmp.begin(), tmp.end());
return (str == tmp) ? true : false;
}
void tokenize(std::string str, std::vector<std::string>& token_v) {
size_t start = str.find_first_not_of(' '), end = start;
while (start != std::string::npos) {
end = str.find(' ', start);
token_v.push_back(str.substr(start, end - start));
start = str.find_first_not_of(' ', end);
}
}
std::string replaceStr(std::string str, const std::string& from, const std::string& to) {
size_t start_pos = 0;
while ((start_pos = str.find(from, start_pos)) != std::string::npos) {
str.replace(start_pos, from.length(), to);
start_pos += to.length();
}
return str;
}