Bitcoin Core  0.20.99
P2P Digital Currency
string.h
Go to the documentation of this file.
1 // Copyright (c) 2019-2020 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 TrimString(const std::string& str, const std::string& pattern = " \f\n\r\t\v")
17 {
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, UnaryOp unary_op)
35  -> decltype(unary_op(list.at(0)))
36 {
37  decltype(unary_op(list.at(0))) ret;
38  for (size_t i = 0; i < list.size(); ++i) {
39  if (i > 0) ret += separator;
40  ret += unary_op(list.at(i));
41  }
42  return ret;
43 }
44 
45 template <typename T>
46 T Join(const std::vector<T>& list, const T& separator)
47 {
48  return Join(list, separator, [](const T& i) { return i; });
49 }
50 
51 // Explicit overload needed for c_str arguments, which would otherwise cause a substitution failure in the template above.
52 inline std::string Join(const std::vector<std::string>& list, const std::string& separator)
53 {
54  return Join<std::string>(list, separator);
55 }
56 
60 NODISCARD inline bool ValidAsCString(const std::string& str) noexcept
61 {
62  return str.size() == strlen(str.c_str());
63 }
64 
68 template <typename T>
69 std::string ToString(const T& t)
70 {
71  std::ostringstream oss;
72  oss.imbue(std::locale::classic());
73  oss << t;
74  return oss.str();
75 }
76 
77 #endif // BITCOIN_UTIL_STRENCODINGS_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:69
NODISCARD std::string TrimString(const std::string &str, const std::string &pattern=" \\\)
Definition: string.h:16
#define NODISCARD
Definition: attributes.h:18