cpp-toolbox  0.0.1
A toolbox library for C++
Loading...
Searching...
No Matches
string.hpp
Go to the documentation of this file.
1#pragma once
2
3#ifndef CPP_TOOLBOX_CONTAINER_STRING_HPP
4# define CPP_TOOLBOX_CONTAINER_STRING_HPP
5
6# include <limits>
7# include <stdexcept>
8# include <string>
9# include <string_view>
10# include <vector>
11
13
15{
41CPP_TOOLBOX_EXPORT auto split(std::string_view str, std::string_view delimiter)
42 -> std::vector<std::string>;
43
68CPP_TOOLBOX_EXPORT auto split(std::string_view str, char delimiter)
69 -> std::vector<std::string>;
70
94CPP_TOOLBOX_EXPORT auto join(const std::vector<std::string>& parts,
95 std::string_view glue) -> std::string;
96
120CPP_TOOLBOX_EXPORT auto join(const std::vector<std::string_view>& parts,
121 std::string_view glue) -> std::string;
122
145CPP_TOOLBOX_EXPORT auto trim_left(std::string_view str) -> std::string;
146
169CPP_TOOLBOX_EXPORT auto trim_right(std::string_view str) -> std::string;
170
192CPP_TOOLBOX_EXPORT auto trim(std::string_view str) -> std::string;
193
216CPP_TOOLBOX_EXPORT auto starts_with(std::string_view s, std::string_view prefix)
217 -> bool;
218
241CPP_TOOLBOX_EXPORT auto ends_with(std::string_view s, std::string_view suffix)
242 -> bool;
243
266CPP_TOOLBOX_EXPORT auto contains(std::string_view s, std::string_view substring)
267 -> bool;
268
293CPP_TOOLBOX_EXPORT auto is_empty_or_whitespace(std::string_view s) -> bool;
294
320CPP_TOOLBOX_EXPORT auto is_numeric(std::string_view s) -> bool;
321
347CPP_TOOLBOX_EXPORT auto is_integer(std::string_view s) -> bool;
348
375CPP_TOOLBOX_EXPORT auto is_float(std::string_view s) -> bool;
376
407 std::string_view s,
408 std::string_view old_value,
409 std::string_view new_value,
410 std::size_t count = std::numeric_limits<std::size_t>::max()) -> std::string;
411
434CPP_TOOLBOX_EXPORT auto replace_all(std::string_view s,
435 std::string_view old_value,
436 std::string_view new_value) -> std::string;
437
468CPP_TOOLBOX_EXPORT auto replace_by_nth(std::string_view s,
469 std::string_view old_value,
470 std::string_view new_value,
471 std::size_t n) -> std::string;
472
502CPP_TOOLBOX_EXPORT auto remove_nth(std::string_view s,
503 std::string_view from,
504 std::size_t n) -> std::string;
505
531 std::string_view s,
532 std::string_view value,
533 std::size_t count = std::numeric_limits<std::size_t>::max()) -> std::string;
534
558CPP_TOOLBOX_EXPORT auto remove_all(std::string_view s, std::string_view value)
559 -> std::string;
560
583CPP_TOOLBOX_EXPORT auto remove_all(std::string_view s, char value)
584 -> std::string;
585
607CPP_TOOLBOX_EXPORT auto to_lower(std::string_view s) -> std::string;
608
630CPP_TOOLBOX_EXPORT auto to_upper(std::string_view s) -> std::string;
631
657CPP_TOOLBOX_EXPORT auto to_string(std::string_view s) -> std::string;
658
685CPP_TOOLBOX_EXPORT auto left_pad(std::string_view s,
686 std::size_t width,
687 char pad_char = ' ') -> std::string;
688
715CPP_TOOLBOX_EXPORT auto right_pad(std::string_view s,
716 std::size_t width,
717 char pad_char = ' ') -> std::string;
718
756CPP_TOOLBOX_EXPORT auto pad(std::string_view s,
757 std::size_t width,
758 char pad_char = ' ',
759 std::size_t position = 0) -> std::string;
760
783CPP_TOOLBOX_EXPORT auto reverse(std::string_view s) -> std::string;
784
821CPP_TOOLBOX_EXPORT auto try_parse_int(std::string_view s, int& out) -> bool;
822
859CPP_TOOLBOX_EXPORT auto try_parse_double(std::string_view s, double& out)
860 -> bool;
861
898CPP_TOOLBOX_EXPORT auto try_parse_float(std::string_view s, float& out) -> bool;
899
928CPP_TOOLBOX_EXPORT auto levenshtein_distance(std::string_view s1,
929 std::string_view s2)
930 -> std::size_t;
931
960 std::string_view s2)
961 -> std::size_t;
962
993 std::string_view s2)
994 -> std::size_t;
995
1025CPP_TOOLBOX_EXPORT auto url_encode(std::string_view s) -> std::string;
1026
1059CPP_TOOLBOX_EXPORT auto url_decode(std::string_view s) -> std::string;
1060
1086CPP_TOOLBOX_EXPORT auto base64_encode(std::string_view data) -> std::string;
1087
1118CPP_TOOLBOX_EXPORT auto base64_decode(std::string_view encoded_data)
1119 -> std::string;
1120
1154CPP_TOOLBOX_EXPORT auto slugify(std::string_view s) -> std::string;
1155
1176CPP_TOOLBOX_EXPORT auto hexview(const char* data,
1177 std::size_t size,
1178 bool with_prefix = true) -> std::string;
1179
1199CPP_TOOLBOX_EXPORT auto hexview(const std::string& data,
1200 bool with_prefix = true) -> std::string;
1201
1222CPP_TOOLBOX_EXPORT auto hexview(const std::vector<char>& data,
1223 bool with_prefix = true) -> std::string;
1224
1245CPP_TOOLBOX_EXPORT auto hexview(const std::vector<std::byte>& data,
1246 bool with_prefix = true) -> std::string;
1247
1269template<typename T>
1270auto hex_to_integral(const std::string& hex_str, bool with_prefix = true) -> T
1271{
1272 static_assert(std::is_integral_v<T>,
1273 "T 必须是整型/T must be an integral type");
1274 std::string_view s(hex_str);
1275 // 跳过可选的 "0x" 或 "0X" 前缀/Skip optional "0x" or "0X" prefix
1276 if (with_prefix && s.size() >= 2 && s[0] == '0'
1277 && (s[1] == 'x' || s[1] == 'X'))
1278 {
1279 s.remove_prefix(2);
1280 }
1281 if (s.empty()) { // Simplified empty check after prefix removal
1282 throw std::invalid_argument(
1283 "非法的十六进制字符串: 空字符串或只有前缀/Invalid hex string: empty or "
1284 "only prefix");
1285 }
1286 // 十六进制字符串长度必须是偶数,除非它是单个 '0' / Hex string length must be
1287 // even, unless it's a single '0'
1288 if (s.size() % 2 != 0 && s != "0") { // 允许单个 "0" / Allow single "0"
1289 throw std::invalid_argument(
1290 "非法的十六进制字符串长度 (必须是偶数,除非是'0')/Invalid hex string "
1291 "length (must be even, unless it's '0')");
1292 }
1293
1294 // 使用 std::stoull 自动处理 base 参数/Use std::stoull to handle base
1295 // parameter automatically
1296 size_t pos = 0; // To check how many characters were consumed
1297 unsigned long long tmp = 0;
1298 try {
1299 tmp = std::stoull(std::string(s), &pos, 16);
1300 } catch (const std::invalid_argument& e) {
1301 // Re-throw with a potentially more informative message if needed, or just
1302 // let it propagate
1303 throw std::invalid_argument("非法的十六进制字符/Invalid hex character(s)");
1304 } catch (const std::out_of_range& e) {
1305 // Let std::out_of_range propagate
1306 throw;
1307 }
1308
1309 // 检查是否所有字符都被消耗/Check if all characters were consumed
1310 if (pos != s.length()) {
1311 throw std::invalid_argument(
1312 "包含非法十六进制字符或尾随字符/Contains invalid hex or trailing "
1313 "characters");
1314 }
1315
1316 // Check for potential overflow when casting back to T (stoull checks against
1317 // ULLONG_MAX) This is a bit tricky, especially for signed types. A simple
1318 // check for unsigned types:
1319 if constexpr (std::is_unsigned_v<T>) {
1320 if (tmp > static_cast<unsigned long long>(std::numeric_limits<T>::max())) {
1321 throw std::out_of_range(
1322 "值超出目标类型范围/Value out of range for target type");
1323 }
1324 } else { // For signed types
1325 // This comparison logic needs careful consideration of T's range
1326 // For simplicity, we might rely on the static_cast behavior or add more
1327 // complex checks if needed. E.g., check if tmp fits within both min and max
1328 // of T if (tmp > static_cast<unsigned long
1329 // long>(std::numeric_limits<T>::max()) &&
1330 // (tmp > -static_cast<long long>(std::numeric_limits<T>::min()) ) ) {
1331 // ... }
1332 // Simpler check: If the original string wasn't negative and result is >
1333 // max, it's overflow
1334 if (tmp > static_cast<unsigned long long>(std::numeric_limits<T>::max())) {
1335 // Check if it could represent a negative number within range if T is
1336 // signed This might require more robust two's complement handling
1337 // depending on exact needs. For now, let's assume stoull parsed correctly
1338 // and cast might overflow. A safer approach might involve parsing
1339 // differently for signed types. Let's keep the basic check for now.
1340 if (tmp > static_cast<unsigned long long>(std::numeric_limits<T>::max()))
1341 {
1342 throw std::out_of_range(
1343 "值超出目标类型范围/Value out of range for target type");
1344 }
1345 }
1346 }
1347
1348 return static_cast<T>(tmp);
1349}
1350
1372template<typename Container>
1373auto hex_to_bytes(const std::string& hex_str, bool with_prefix = true)
1374 -> Container
1375{
1376 using Byte = typename Container::value_type;
1377 std::string_view s(hex_str);
1378 if (with_prefix && s.size() >= 2 && s[0] == '0'
1379 && (s[1] == 'x' || s[1] == 'X'))
1380 {
1381 s.remove_prefix(2);
1382 }
1383 if (s.size() % 2 != 0) {
1384 throw std::invalid_argument(
1385 "十六进制字符串长度必须是偶数/Hex string length must be even");
1386 }
1387 Container output;
1388 output.clear();
1389 output.reserve(s.size() / 2);
1390 for (size_t i = 0; i < s.size(); i += 2) {
1391 auto hi = s[i];
1392 auto lo = s[i + 1];
1393 if (!std::isxdigit(hi) || !std::isxdigit(lo)) {
1394 throw std::invalid_argument(
1395 "包含非法十六进制字符/Contains invalid hex characters");
1396 }
1397 Byte byte = static_cast<Byte>(
1398 ((std::isdigit(hi) ? hi - '0' : std::toupper(hi) - 'A' + 10) * 16)
1399 + (std::isdigit(lo) ? lo - '0' : std::toupper(lo) - 'A' + 10));
1400 output.push_back(byte);
1401 }
1402 return output;
1403}
1404
1405} // namespace toolbox::container::string
1406#endif // CPP_TOOLBOX_CONTAINER_STRING_HPP
#define CPP_TOOLBOX_EXPORT
Definition export.hpp:8
Definition string.hpp:15
CPP_TOOLBOX_EXPORT auto left_pad(std::string_view s, std::size_t width, char pad_char=' ') -> std::string
在字符串左侧填充指定字符以达到最小宽度 / Pads a string on the left with a specified character to reach a minimum width
Definition string.cpp:568
CPP_TOOLBOX_EXPORT auto try_parse_float(std::string_view s, float &out) -> bool
尝试从字符串视图解析单精度浮点数 / Attempts to parse a single-precision floating-point number from a string view
Definition string.cpp:661
CPP_TOOLBOX_EXPORT auto split(std::string_view str, std::string_view delimiter) -> std::vector< std::string >
使用字符串分隔符将字符串视图分割成字符串向量 / Splits a string view into a vector of strings based on a string delimiter.
Definition string.cpp:26
CPP_TOOLBOX_EXPORT auto remove_all(std::string_view s, std::string_view value) -> std::string
从字符串视图中删除所有出现的子字符串 / Removes all occurrences of a substring from a string view
Definition string.cpp:520
CPP_TOOLBOX_EXPORT auto hexview(const char *data, std::size_t size, bool with_prefix=true) -> std::string
将二进制数据转换为十六进制字符串表示/Convert binary data to hexadecimal string representation
Definition string.cpp:1093
CPP_TOOLBOX_EXPORT auto levenshtein_distance(std::string_view s1, std::string_view s2) -> std::size_t
计算两个字符串之间的Levenshtein距离 / Calculates the Levenshtein distance between two strings
Definition string.cpp:689
CPP_TOOLBOX_EXPORT auto url_encode(std::string_view s) -> std::string
对字符串进行百分比编码以安全地包含在URL中 / Percent-encodes a string for safe inclusion in a URL
Definition string.cpp:822
CPP_TOOLBOX_EXPORT auto to_lower(std::string_view s) -> std::string
将字符串视图中的所有字符转换为小写 / Converts all characters in a string view to lowercase
Definition string.cpp:540
CPP_TOOLBOX_EXPORT auto base64_encode(std::string_view data) -> std::string
将二进制数据(以字符串视图表示)编码为Base64格式 / Encodes binary data (represented as a string_view) into Base64 format
Definition string.cpp:921
CPP_TOOLBOX_EXPORT auto remove_nth(std::string_view s, std::string_view from, std::size_t n) -> std::string
删除字符串中第N次出现的子字符串 / Removes the Nth occurrence of a substring within a string
Definition string.cpp:486
CPP_TOOLBOX_EXPORT auto replace_all(std::string_view s, std::string_view old_value, std::string_view new_value) -> std::string
替换字符串视图中所有出现的子字符串 / Replaces all occurrences of a substring within a string view
Definition string.cpp:433
CPP_TOOLBOX_EXPORT auto ends_with(std::string_view s, std::string_view suffix) -> bool
检查字符串视图是否以指定后缀结尾 / Checks if a string view ends with a specified suffix
Definition string.cpp:164
CPP_TOOLBOX_EXPORT auto join(const std::vector< std::string > &parts, std::string_view glue) -> std::string
使用连接字符串将字符串向量连接成单个字符串 / Joins a vector of strings into a single string, separated by a glue string
Definition string.cpp:72
CPP_TOOLBOX_EXPORT auto replace_by_nth(std::string_view s, std::string_view old_value, std::string_view new_value, std::size_t n) -> std::string
替换字符串中第N次出现的子字符串 / Replaces the Nth occurrence of a substring within a string
Definition string.cpp:443
CPP_TOOLBOX_EXPORT auto to_string(std::string_view s) -> std::string
将字符串视图转换为标准字符串 / Converts a string view to a standard string
Definition string.cpp:562
CPP_TOOLBOX_EXPORT auto to_upper(std::string_view s) -> std::string
将字符串视图中的所有字符转换为大写 / Converts all characters in a string view to uppercase
Definition string.cpp:551
CPP_TOOLBOX_EXPORT auto starts_with(std::string_view s, std::string_view prefix) -> bool
检查字符串视图是否以指定前缀开头 / Checks if a string view starts with a specified prefix
Definition string.cpp:157
CPP_TOOLBOX_EXPORT auto contains(std::string_view s, std::string_view substring) -> bool
检查字符串视图是否包含指定子字符串 / Checks if a string view contains a specified substring
Definition string.cpp:172
CPP_TOOLBOX_EXPORT auto pad(std::string_view s, std::size_t width, char pad_char=' ', std::size_t position=0) -> std::string
使用指定字符填充字符串以达到最小宽度,可控制填充位置 / Pads a string with a specified character to reach a minimum width,...
Definition string.cpp:598
CPP_TOOLBOX_EXPORT auto remove(std::string_view s, std::string_view value, std::size_t count=std::numeric_limits< std::size_t >::max()) -> std::string
从字符串视图中删除子字符串的出现,最多删除指定次数 / Removes occurrences of a substring from a string view,...
Definition string.cpp:494
CPP_TOOLBOX_EXPORT auto replace(std::string_view s, std::string_view old_value, std::string_view new_value, std::size_t count=std::numeric_limits< std::size_t >::max()) -> std::string
在字符串视图中将一个子字符串替换为另一个子字符串,最多替换指定次数 / Replaces occurrences of a substring within a string view with ano...
Definition string.cpp:378
auto hex_to_integral(const std::string &hex_str, bool with_prefix=true) -> T
将十六进制字符串转换为整数类型/Convert hexadecimal string to integral type
Definition string.hpp:1270
CPP_TOOLBOX_EXPORT auto base64_decode(std::string_view encoded_data) -> std::string
将Base64编码的字符串解码回原始数据 / Decodes a Base64 encoded string back into its original data
Definition string.cpp:978
CPP_TOOLBOX_EXPORT auto longest_common_subsequence_length(std::string_view s1, std::string_view s2) -> std::size_t
计算两个字符串的最长公共子序列(LCS)长度 / Calculates the length of the Longest Common Subsequence (LCS) of two strings
Definition string.cpp:744
CPP_TOOLBOX_EXPORT auto trim_left(std::string_view str) -> std::string
删除字符串视图开头的空白字符 / Removes leading whitespace characters from a string view
Definition string.cpp:127
CPP_TOOLBOX_EXPORT auto url_decode(std::string_view s) -> std::string
解码百分比编码的字符串(URL解码) / Decodes a percent-encoded string (URL decoding)
Definition string.cpp:847
auto hex_to_bytes(const std::string &hex_str, bool with_prefix=true) -> Container
将十六进制字符串转换为字节容器/Convert hexadecimal string to byte container
Definition string.hpp:1373
CPP_TOOLBOX_EXPORT auto reverse(std::string_view s) -> std::string
反转字符串视图中字符的顺序 / Reverses the order of characters in a string view
Definition string.cpp:612
CPP_TOOLBOX_EXPORT auto try_parse_double(std::string_view s, double &out) -> bool
尝试从字符串视图解析双精度浮点数 / Attempts to parse a double-precision floating-point number from a string view
Definition string.cpp:632
CPP_TOOLBOX_EXPORT auto is_empty_or_whitespace(std::string_view s) -> bool
检查字符串视图是否为空或仅包含空白字符 / Checks if a string view is empty or consists only of whitespace characters
Definition string.cpp:178
CPP_TOOLBOX_EXPORT auto right_pad(std::string_view s, std::size_t width, char pad_char=' ') -> std::string
在字符串右侧填充指定字符以达到最小宽度 / Pads a string on the right with a specified character to reach a minimum width
Definition string.cpp:582
CPP_TOOLBOX_EXPORT auto is_numeric(std::string_view s) -> bool
检查字符串视图是否表示数值(整数或浮点数)/ Checks if a string view represents a numeric value (integer or floating-point)
Definition string.cpp:214
CPP_TOOLBOX_EXPORT auto is_integer(std::string_view s) -> bool
检查字符串视图是否表示有效的整数值 / Checks if a string view represents a valid integer value
Definition string.cpp:184
CPP_TOOLBOX_EXPORT auto slugify(std::string_view s) -> std::string
将字符串转换为URL友好的"slug" / Converts a string into a URL-friendly "slug"
Definition string.cpp:1036
CPP_TOOLBOX_EXPORT auto try_parse_int(std::string_view s, int &out) -> bool
尝试从字符串视图解析整数 / Attempts to parse an integer from a string view
Definition string.cpp:620
CPP_TOOLBOX_EXPORT auto trim(std::string_view str) -> std::string
删除字符串视图两端的空白字符 / Removes both leading and trailing whitespace characters from a string view
Definition string.cpp:145
CPP_TOOLBOX_EXPORT auto longest_common_substring_length(std::string_view s1, std::string_view s2) -> std::size_t
计算两个字符串的最长公共子串长度 / Calculates the length of the Longest Common Substring of two strings
Definition string.cpp:784
CPP_TOOLBOX_EXPORT auto trim_right(std::string_view str) -> std::string
删除字符串视图末尾的空白字符 / Removes trailing whitespace characters from a string view
Definition string.cpp:134
CPP_TOOLBOX_EXPORT auto is_float(std::string_view s) -> bool
检查字符串视图是否表示有效的浮点数值 / Checks if a string view represents a valid floating-point value
Definition string.cpp:297