licornea_tools
string.cc
Go to the documentation of this file.
1 #include "string.h"
2 #include <string>
3 #include <sstream>
4 #include <cstdio>
5 #include <cctype>
6 
7 namespace tlz {
8 
9 std::string file_name_extension(const std::string& filename) {
10  std::ptrdiff_t pos = filename.find_last_of('.');
11  if(pos == std::string::npos) return "";
12  else return filename.substr(pos + 1);
13 }
14 
15 std::vector<std::string> explode(char separator, const std::string& str) {
16  std::vector<std::string> vec;
17  std::string::size_type last_pos = 0;
18  std::string::size_type pos = str.find(separator);
19  while(pos != std::string::npos) {
20  std::string::size_type n = pos - last_pos;
21  std::string part = str.substr(last_pos, n);
22  vec.push_back(part);
23  last_pos = pos + 1;
24  pos = str.find(separator, last_pos);
25  }
26  vec.push_back(str.substr(last_pos));
27  return vec;
28 }
29 
30 
31 std::string implode(char separator, const std::vector<std::string>& vec) {
32  std::ostringstream ostr;
33  auto last = vec.end() - 1;
34  for(auto it = vec.begin(); it != last; ++it) {
35  ostr << *it << separator;
36  }
37  ostr << vec.back();
38  return ostr.str();
39 }
40 
41 
42 std::string to_lower(const std::string& s_orig) {
43  std::string s(s_orig);
44  for(char& c: s) c = std::tolower(c);
45  return s;
46 }
47 
48 
49 std::string to_upper(const std::string& s_orig) {
50  std::string s(s_orig);
51  for(char& c: s) c = std::toupper(c);
52  return s;
53 }
54 
55 
56 std::string replace_all(const std::string& subject_orig, const std::string& find, const std::string& replace) {
57  std::string subject = subject_orig;
58  replace_all_inplace(subject, find, replace);
59  return subject;
60 }
61 
62 
63 std::size_t replace_all_inplace(std::string& subject, const std::string& find, const std::string& replace) {
64  std::size_t pos = 0;
65  std::size_t count = 0;
66  while( (pos = subject.find(find, pos)) != std::string::npos ) {
67  subject.replace(pos, find.length(), replace);
68  pos += replace.length();
69  ++count;
70  }
71  return count;
72 }
73 
74 
75 int string_hash(const std::string& str) {
76  int h = 0;
77  for(char c : str) h += c;
78  return h;
79 }
80 
81 }
std::size_t replace_all_inplace(std::string &subject, const std::string &find, const std::string &replace)
Definition: string.cc:63
std::string implode(char separator, const std::vector< std::string > &vec)
Definition: string.cc:31
int string_hash(const std::string &str)
Definition: string.cc:75
std::string replace_all(const std::string &subject_orig, const std::string &find, const std::string &replace)
Definition: string.cc:56
std::string to_upper(const std::string &s_orig)
Definition: string.cc:49
std::string file_name_extension(const std::string &filename)
Definition: string.cc:9
std::string to_lower(const std::string &s_orig)
Definition: string.cc:42
std::vector< std::string > explode(char separator, const std::string &str)
Definition: string.cc:15