DaZeus  2.0
 All Classes Namespaces Files Functions Variables Enumerations Enumerator Friends Macros
utils.cpp
Go to the documentation of this file.
1 /*
2  * Copyright (c) Sjors Gielen, 2010-2012
3  * See LICENSE for license.
4  */
5 
6 #include "utils.h"
7 
8 std::string strToLower(const std::string &f) {
9  std::string res;
10  res.reserve(f.length());
11  for(unsigned i = 0; i < f.length(); ++i) {
12  res.push_back(tolower(f[i]));
13  }
14  return res;
15 }
16 
17 std::string strToUpper(const std::string &f) {
18  std::string res;
19  res.reserve(f.length());
20  for(unsigned i = 0; i < f.length(); ++i) {
21  res.push_back(toupper(f[i]));
22  }
23  return res;
24 }
25 
26 std::string strToIdentifier(const std::string &f) {
27  std::string res;
28  res.reserve(f.length());
29  for(unsigned i = 0; i < f.length(); ++i) {
30  if(!isalpha(f[i])) continue;
31  res.push_back(tolower(f[i]));
32  }
33  return res;
34 }
35 
36 std::string trim(const std::string &s) {
37  std::string str;
38  bool alpha = true;
39  for(unsigned i = 0; i < s.length(); ++i) {
40  if(alpha && isspace(s[i]))
41  continue;
42  alpha = false;
43  str += s[i];
44  }
45  for(int i = str.length() - 1; i >= 0; --i) {
46  if(isspace(str[i]))
47  str.resize(i);
48  else break;
49  }
50  return str;
51 }
52 
53 bool contains(std::string x, char v) {
54  return find(x.begin(), x.end(), v) != x.end();
55 }
56 
57 bool startsWith(std::string x, std::string y, bool caseInsensitive)
58 {
59  std::string z = x.substr(0, y.length());
60  if(caseInsensitive)
61  return strToLower(z) == strToLower(y);
62  else return z == y;
63 }
64 
65 std::vector<std::string> split(const std::string &s, const std::string &sep)
66 {
67  std::vector<std::string> res;
68  std::string s_ = s;
69  int len = sep.length();
70  int remaining = s.length();
71  for(int i = 0; i <= remaining - len; ++i) {
72  if(s_.substr(i, len) == sep) {
73  res.push_back(s_.substr(0, i));
74  s_ = s_.substr(i + sep.length());
75  remaining -= i + sep.length();
76  i = -1;
77  }
78  }
79  res.push_back(s_);
80  return res;
81 }
82 
83 std::vector<std::string> &operator<<(std::vector<std::string> &x, const char *v) {
84  x << std::string(v);
85  return x;
86 }
87 
88 std::vector<std::string>::iterator find_ci(std::vector<std::string> &v, const std::string &s) {
89  std::string sl = strToLower(s);
90  std::vector<std::string>::iterator it;
91  for(it = v.begin(); it != v.end(); ++it) {
92  if(strToLower(*it) == sl) {
93  return it;
94  }
95  }
96  return v.end();
97 }
98