All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
StringTools.h
Go to the documentation of this file.
1 /*
2  * StringTools.h
3  *
4  * Completely rewritten on: 12.05.2014
5  * Author: Florian Weber (uagws@student.kit.edu)
6  */
7 
8 #ifndef STRINGTOOLS_H_
9 #define STRINGTOOLS_H_
10 
11 #include <algorithm>
12 #include <vector>
13 #include <string>
14 
15 namespace Aux {
16 
20 namespace StringTools {
21 
30 template<typename Iterator, typename Character>
31 std::vector<std::string> split(Iterator begin, Iterator end, Character delim = Character{' '}) {
32 
33  // measurements showed that precalculating the number of tokens and
34  // reserving space for them was in fact slower than just letting
35  // the vector grow naturally.
36  std::vector<std::string> tokens;
37 
38  auto it = begin;
39  while (it != end) {
40  auto tmp = std::find(it, end, delim);
41  tokens.emplace_back(it, tmp);
42  if (tmp == end) {
43  break;
44  }
45  it = tmp;
46  ++it;
47 
48  }
49  return tokens;
50 }
51 
55 inline std::vector<std::string> split(const std::string& s, char delim = ' ') {
56  return split(s.begin(), s.end(), delim);
57 }
58 
62 inline bool ends_with(const std::string& str, const std::string& suffix) {
63  return str.size() >= suffix.size() &&
64  str.compare(str.size() - suffix.size(), suffix.size(), suffix) == 0;
65 }
66 
70 inline bool starts_with(const std::string& str, const std::string& prefix) {
71  return str.size() >= prefix.size() &&
72  str.compare(0, prefix.size(), prefix) == 0;
73 }
74 
75 } /* namespace StringTools */
76 } /* namespace Aux */
77 #endif /* STRINGTOOLS_H_ */
std::vector< std::string > split(Iterator begin, Iterator end, Character delim=Character{' '})
Splits a range of characters at a delimiter into a vector of strings.
Definition: StringTools.h:31
bool starts_with(const std::string &str, const std::string &prefix)
Determines whether str starts with prefix.
Definition: StringTools.h:70
bool ends_with(const std::string &str, const std::string &suffix)
Determines whether str ends with suffix.
Definition: StringTools.h:62