Thrill  0.1
erase_all.cpp
Go to the documentation of this file.
1 /*******************************************************************************
2  * tlx/string/erase_all.cpp
3  *
4  * Part of tlx - http://panthema.net/tlx
5  *
6  * Copyright (C) 2007-2017 Timo Bingmann <[email protected]>
7  *
8  * All rights reserved. Published under the Boost Software License, Version 1.0
9  ******************************************************************************/
10 
11 #include <tlx/string/erase_all.hpp>
12 
13 namespace tlx {
14 
15 /******************************************************************************/
16 // erase_all() in-place
17 
18 std::string& erase_all(std::string* str, char drop) {
19  std::string::size_type pos1 = std::string::npos, pos2;
20 
21  while ((pos1 = str->find_last_of(drop, pos1)) != std::string::npos) {
22  pos2 = str->find_last_not_of(drop, pos1);
23  if (pos2 == std::string::npos) {
24  str->erase(0, pos1 - pos2);
25  return *str;
26  }
27  str->erase(pos2 + 1, pos1 - pos2);
28  pos1 = pos2;
29  }
30 
31  return *str;
32 }
33 
34 std::string& erase_all(std::string* str, const char* drop) {
35  std::string::size_type pos1 = std::string::npos, pos2;
36 
37  while ((pos1 = str->find_last_of(drop, pos1)) != std::string::npos) {
38  pos2 = str->find_last_not_of(drop, pos1);
39  if (pos2 == std::string::npos) {
40  str->erase(0, pos1 - pos2);
41  return *str;
42  }
43  str->erase(pos2 + 1, pos1 - pos2);
44  pos1 = pos2;
45  }
46 
47  return *str;
48 }
49 
51  return erase_all(str, drop.c_str());
52 }
53 
54 /******************************************************************************/
55 // erase_all() copy
56 
57 std::string erase_all(const std::string& str, char drop) {
58  std::string out;
59  out.reserve(str.size());
60 
61  std::string::const_iterator si = str.begin();
62  while (si != str.end()) {
63  if (*si != drop)
64  out += *si;
65  ++si;
66  }
67 
68  return out;
69 }
70 
71 std::string erase_all(const std::string& str, const char* drop) {
72  std::string out;
73  out.reserve(str.size());
74 
75  std::string::const_iterator si = str.begin();
76  while (si != str.end()) {
77  // search for letter
78  const char* d = drop;
79  while (*d != 0) {
80  if (*si == *d) break;
81  ++d;
82  }
83  // append if not found
84  if (*d == 0)
85  out += *si;
86  ++si;
87  }
88 
89  return out;
90 }
91 
92 std::string erase_all(const std::string& str, const std::string& drop) {
93  return erase_all(str, drop.c_str());
94 }
95 
96 } // namespace tlx
97 
98 /******************************************************************************/
std::string & erase_all(std::string *str, char drop)
Remove all occurrences of the given character in-place.
Definition: erase_all.cpp:18
std::basic_string< char, std::char_traits< char >, Allocator< char > > string
string with Manager tracking
Definition: allocator.hpp:220