表格线识别通用库文档
载入中...
搜索中...
未找到
string.hpp
浏览该文件的文档.
1/*
2 * @Description: 字符串工具函数 头文件及其实现
3 * @Version:
4 * @Autor: dreamy-xay
5 * @date: 2023-12-14
6 * @LastEditors: dreamy-xay
7 * @LastEditTime: 2024-03-01
8 */
9
10#ifndef COMMON_UTILS_STRING_HPP
11#define COMMON_UTILS_STRING_HPP
12
13#include <cstdarg>
14#include <cstring>
15#include <string>
16
17#include "common/enum.h"
18#include "common/macro.h"
19#include "common/type.h"
20#include "common/base/list.hpp"
21
22/* declare */
23namespace cm {
24
25std::string Sprintf(const char* format, ...);
26List<std::string> Ssplit(const std::string& original_str, const char* delimiter);
27
28} // namespace cm
29
30/* implement */
31namespace cm {
32
47inline std::string Sprintf(const char* format, ...) {
48 va_list args; // 定义va_list类型变量
49 va_start(args, format); // 初始化va_list变量
50
51 // 获取格式化字符串的长度
52 int length = std::vsnprintf(nullptr, 0, format, args); // flawfinder: ignore
53 va_end(args);
54
55 std::string result;
56
57 if (length >= 0) {
58 result.resize(length); // 如果实际需要的大小超过了初始分配的大小,重新调整缓冲区大小(增加一个字符用于存储终止符 '\0')
59
61 // flawfinder: ignore
62 std::vsnprintf(&result[0], length + 1, format, args); // 重新格式化字符串
63 va_end(args);
64 }
65
66 return std::move(result); // 将结果转换为std::string并返回
67}
68
80inline List<std::string> Ssplit(const std::string& original_str, const char* delimiter) {
81 List<std::string> result; // 结果数组
82
83 // flawfinder: ignore
84 if (strlen(delimiter) == 0) // 如果字符串长度为0,则不处理
85 return result;
86
87 // 查找分隔符开始索引和查找到的索引
88 std::size_t start = 0, index = original_str.find_first_of(delimiter, 0);
89
90 // 查找整个字符串
91 while (index != original_str.npos) {
92 if (start != index) // 如果不是第一个字符,则将字符串添加到结果数组中
93 result.push_back(original_str.substr(start, index - start));
94
95 start = index + 1; // 更新查找开始索引
96
97 index = original_str.find_first_of(delimiter, start); // 查找下一个分隔符索引
98 }
99
100 if (start < original_str.size()) // 如果不是最后一个字符,则将字符串添加到结果数组中
101 result.push_back(original_str.substr(start));
102
103 return std::move(result);
104}
105
106} // namespace cm
107
108
109#endif
点类
Definition point.hpp:52
std::string Sprintf(const char *format,...)
格式化输出字符串
Definition string.hpp:47
List< std::string > Ssplit(const std::string &original_str, const char *delimiter)
字符串分割函数
Definition string.hpp:80