Created
March 23, 2017 09:57
-
-
Save gelldur/5d40e1d54ba549c6a6080146621ebc96 to your computer and use it in GitHub Desktop.
Reverse words in text
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <algorithm> | |
#include <cstring> | |
template<class T, class UnaryPredicate> | |
void reverseStringExtra(T& text, const UnaryPredicate& predicate) | |
{ | |
auto previousPivot = std::begin(text); | |
auto pivot = previousPivot; | |
while ((pivot = std::find_if(pivot, std::end(text), predicate)) != std::end(text)) | |
{ | |
std::reverse(previousPivot, pivot); | |
pivot = previousPivot = std::next(pivot); | |
} | |
std::reverse(previousPivot, std::end(text)); | |
} | |
/** | |
* Prefer to use std algorithms. | |
* I want make it short and elegant and maintainable :) | |
* @param text | |
*/ | |
template<class T> | |
void reverseString(T& text, char delim = ' ') | |
{ | |
reverseStringExtra(text, [&](auto element) | |
{ | |
return element == delim; | |
}); | |
} | |
int main() | |
{ | |
std::string text = "single"; | |
std::cout << text << std::endl; | |
reverseString(text); | |
std::cout << text << std::endl; | |
char cStringSingle[] = {'s', 'i', 'n', 'g', 'l', 'e'}; | |
std::cout << cStringSingle << std::endl; | |
reverseString(cStringSingle);//Fun fact :d | |
std::cout << cStringSingle << std::endl; | |
text = "I love C++! and?\t";//our delim is ' ' char not \t | |
std::cout << text << std::endl; | |
reverseString(text); | |
std::cout << text << std::endl; | |
text = u8"oką©ę";//sorry no time for UTF8 but it would be easy to write if i need to, or use wstring | |
std::cout << text << std::endl; | |
reverseString(text); | |
std::cout << text << std::endl; | |
//Thx to template and std::begin, std::end, std::next | |
char cString[] = "I like templates";//lookout for extra \0 on end :P | |
std::cout << cString << std::endl; | |
reverseString(cString);//Fun fact :d #2 | |
std::cout << cString << std::endl; | |
//Palindrome ;) | |
text = "kajak"; | |
std::cout << text << std::endl; | |
reverseString(text); | |
std::cout << text << std::endl; | |
//Test wstring | |
std::wstring utf8One{L"ążźć"}; | |
std::wcout << utf8One << std::endl; | |
reverseString(utf8One); | |
std::wcout << utf8One << std::endl; | |
//Custom delim | |
text = "I love C++! Java\nand?\tC#:<"; | |
std::cout << text << std::endl; | |
reverseStringExtra(text, isspace); | |
std::cout << text << std::endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment