Advertisement
Guest User

to_slug

a guest
Mar 5th, 2015
302
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.27 KB | None | 0 0
  1. template <typename InputIterator, typename OutputIterator>
  2. auto to_slug(InputIterator first, InputIterator last, OutputIterator out, std::locale const& locale)
  3.     -> std::pair<OutputIterator, bool>
  4. {
  5.     using char_t = decltype(*first);
  6.     constexpr auto hyphen = char_t {'-'};
  7.  
  8.     auto const next = [&](InputIterator it) {
  9.         return std::find_if(it, last, [&](char_t ch) {
  10.             return std::isalnum(ch, locale);
  11.         });
  12.     };
  13.  
  14.     auto it = next(first);
  15.     if (it == last) {
  16.         return std::make_pair(out, false);
  17.     }
  18.  
  19.     bool const is_digit = std::isdigit(*it, locale);
  20.     out++ = std::tolower(*it++, locale);
  21.  
  22.     while (it != last) {
  23.         if (std::isalnum(*it, locale)) {
  24.             out++ = std::tolower(*it++, locale);
  25.         } else if ((it = next(++it)) != last) {
  26.             out++ = hyphen;
  27.         }
  28.     }
  29.  
  30.     return std::make_pair(out, !is_digit);
  31. }
  32.  
  33. template <typename InputIterator, typename OutputIterator>
  34. auto to_slug(InputIterator first, InputIterator last, OutputIterator out) {
  35.     return to_slug(first, last, out, std::locale::classic());
  36. }
  37.  
  38. void main() {
  39.     to_slug(std::istream_iterator<char>(std::cin)
  40.           , std::istream_iterator<char>()
  41.           , std::ostream_iterator<char>(std::cout));
  42. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement