TorchCraftAI
A bot for machine learning research on StarCraft: Brood War
str.h
1 /*
2  * Copyright (c) 2017-present, Facebook, Inc.
3  *
4  * This source code is licensed under the MIT license found in the
5  * LICENSE file in the root directory of this source tree.
6  */
7 
8 #pragma once
9 
10 #include <algorithm>
11 #include <cstring>
12 #include <sstream>
13 #include <string>
14 #include <vector>
15 
16 namespace common {
17 
18 template <typename T>
19 std::string stringToLower(T&& str);
20 
21 /**
22  * Split a string into parts deliminted by the given separtion character.
23  *
24  * This will repeatedly call `getline()` with `sep` as the delimitation
25  * character. If `max` is >= 0, at most `max` splits will be performed
26  * (cf. Python's split() function).
27  */
28 std::vector<std::string>
29 stringSplit(char const* str, size_t len, char sep, size_t max = -1);
30 
31 std::vector<std::string>
32 stringSplit(char const* str, char sep, size_t max = -1);
33 
34 std::vector<std::string>
35 stringSplit(std::string const& str, char sep, size_t max = -1);
36 
37 template <typename T>
38 std::string joinVector(std::vector<T> const& v, char sep);
39 
40 bool startsWith(std::string const& str, std::string const& prefix);
41 
42 bool endsWith(std::string const& str, std::string const& suffix);
43 
44 /// Glob-style pattern matching
45 bool gmatch(std::string_view str, std::string_view pattern);
46 
47 /// Glob-style pattern matching (case-insensitive)
48 bool gmatchi(std::string_view str, std::string_view pattern);
49 
50 /**************** IMPLEMENTATIONS ********************/
51 
52 template <typename T>
53 std::string stringToLower(T&& str) {
54  std::string lowered;
55  lowered.resize(str.size());
56  std::transform(str.begin(), str.end(), lowered.begin(), tolower);
57  return lowered;
58 }
59 
60 template <typename T>
61 std::string joinVector(std::vector<T> const& v, char sep) {
62  std::ostringstream oss;
63  for (size_t i = 0; i < v.size(); i++) {
64  if (i > 0) {
65  oss << sep;
66  }
67  oss << v[i];
68  }
69  return oss.str();
70 }
71 
72 } // namespace common
std::string stringToLower(T &&str)
Definition: str.h:53
bool endsWith(std::string const &str, std::string const &suffix)
Definition: str.cpp:194
bool gmatchi(std::string_view str, std::string_view pattern)
Glob-style pattern matching (case-insensitive)
Definition: str.cpp:206
bool gmatch(std::string_view str, std::string_view pattern)
Glob-style pattern matching.
Definition: str.cpp:201
std::string joinVector(std::vector< T > const &v, char sep)
Definition: str.h:61
General utilities.
Definition: assert.cpp:7
std::vector< std::string > stringSplit(char const *str, size_t len, char sep, size_t max)
Split a string into parts deliminted by the given separtion character.
Definition: str.cpp:152
bool startsWith(std::string const &str, std::string const &prefix)
Definition: str.cpp:187