trim.cpp

(plain text)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#include <boost/config.hpp>
#include <boost/functional.hpp>
#include <algorithm>
#include <functional>
#include <iostream>
#include <iterator>
#include <string>
#include <cctype>

#ifndef BOOST_NO_STD_LOCALE
#  include <locale>
#  define ISSPACE(E, loc) boost::bind2nd(&std::isspace<E>, loc)
#else
#  define ISSPACE(E, loc) std::ptr_fun(&std::isspace)
  namespace std {
    class locale { };
    std::istream &wcin = cin;
    std::ostream &wcout = cout;
    std::ostream &wcerr = cerr;
    std::ostream &wclog = clog;
  }
#endif

template <typename E, typename It>
It first_nospace (It first, It last, const std::locale &loc = std::locale()) {
  return std::find_if(first, last, std::not1(ISSPACE(E, loc)));
}

template <typename E, typename T, typename A>
std::basic_string<E, T, A> ltrim (const std::basic_string<E, T, A> &s,
                                  const std::locale &loc = std::locale()) {
  return std::basic_string<E, T, A>(first_nospace<E>(s.begin(), s.end(), loc),
                                    s.end());
}

template <typename E, typename T, typename A>
std::basic_string<E, T, A> rtrim (const std::basic_string<E, T, A> &s,
                                  const std::locale &loc = std::locale()) {
  return std::basic_string<E, T, A>(s.begin(),
                                    first_nospace<E>(s.rbegin(), s.rend(), loc).base());
}

template <typename E, typename T, typename A>
std::basic_string<E, T, A>  trim (const std::basic_string<E, T, A> &s,
                                  const std::locale &loc = std::locale()) {
  return std::basic_string<E, T, A>(first_nospace<E>(s.begin(), s.end(), loc),
                                    first_nospace<E>(s.rbegin(), s.rend(), loc).base());
}

template <typename E>
std::basic_string<E> ltrim (const E *p) {
  return ltrim(std::basic_string<E>(p));
}

template <typename E>
std::basic_string<E> rtrim (const E *p) {
  return rtrim(std::basic_string<E>(p));
}

template <typename E>
std::basic_string<E> trim (const E *p) {
  return trim(std::basic_string<E>(p));
}

int main () {
  std::cout << '[' << ltrim("   hi mom   ") << ']' << std::endl;
  std::cout << '[' << rtrim("   hi mom   ") << ']' << std::endl;
  std::cout << '[' << trim("   hi mom   ") << ']' << std::endl;

  std::basic_string<wchar_t> w(L"   hi mom   ");
     
  std::wcout << '[' << ltrim(w) << ']' << std::endl;
  std::wcout << '[' << rtrim(w) << ']' << std::endl;
  std::wcout << '[' << trim(w) << ']' << std::endl;
}