Bitcoin ABC  0.22.13
P2P Digital Currency
string.h
Go to the documentation of this file.
1 // Copyright (c) 2019 The Bitcoin Core developers
2 // Distributed under the MIT software license, see the accompanying
3 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
4 
5 #ifndef BITCOIN_UTIL_STRING_H
6 #define BITCOIN_UTIL_STRING_H
7 
8 #include <attributes.h>
9 
10 #include <cstring>
11 #include <locale>
12 #include <sstream>
13 #include <string>
14 #include <vector>
15 
16 NODISCARD inline std::string
17 TrimString(const std::string &str, const std::string &pattern = " \f\n\r\t\v") {
18  std::string::size_type front = str.find_first_not_of(pattern);
19  if (front == std::string::npos) {
20  return std::string();
21  }
22  std::string::size_type end = str.find_last_not_of(pattern);
23  return str.substr(front, end - front + 1);
24 }
25 
33 template <typename T, typename BaseType, typename UnaryOp>
34 auto Join(const std::vector<T> &list, const BaseType &separator,
35  UnaryOp unary_op) -> decltype(unary_op(list.at(0))) {
36  decltype(unary_op(list.at(0))) ret;
37  for (size_t i = 0; i < list.size(); ++i) {
38  if (i > 0) {
39  ret += separator;
40  }
41  ret += unary_op(list.at(i));
42  }
43  return ret;
44 }
45 
46 template <typename T> T Join(const std::vector<T> &list, const T &separator) {
47  return Join(list, separator, [](const T &i) { return i; });
48 }
49 
50 // Explicit overload needed for c_str arguments, which would otherwise cause a
51 // substitution failure in the template above.
52 inline std::string Join(const std::vector<std::string> &list,
53  const std::string &separator) {
54  return Join<std::string>(list, separator);
55 }
56 
60 NODISCARD inline bool ValidAsCString(const std::string &str) noexcept {
61  return str.size() == strlen(str.c_str());
62 }
63 
67 template <typename T> std::string ToString(const T &t) {
68  std::ostringstream oss;
69  oss.imbue(std::locale::classic());
70  oss << t;
71  return oss.str();
72 }
73 
74 #endif // BITCOIN_UTIL_STRING_H
auto Join(const std::vector< T > &list, const BaseType &separator, UnaryOp unary_op) -> decltype(unary_op(list.at(0)))
Join a list of items.
Definition: string.h:34
NODISCARD bool ValidAsCString(const std::string &str) noexcept
Check if a string does not contain any embedded NUL (\0) characters.
Definition: string.h:60
std::string ToString(const T &t)
Locale-independent version of std::to_string.
Definition: string.h:67
NODISCARD std::string TrimString(const std::string &str, const std::string &pattern=" \\\)
Definition: string.h:17
#define NODISCARD
Definition: attributes.h:18