Skip to content

Instantly share code, notes, and snippets.

@mightbxg
Last active Nov 24, 2022
Embed
What would you like to do?
commonly used utilities in C++
/// @brief String format from OpenCV
inline std::string format(const char* fmt, ...)
{
std::vector<char> buf(1024);
while (true) {
va_list va;
va_start(va, fmt);
int bsize = static_cast<int>(buf.size());
int len = std::vsnprintf(buf.data(), bsize, fmt, va);
va_end(va);
assert(len >= 0);
if (len >= bsize){
buf.resize(len + 1);
continue;
}
buf[bsize - 1] = 0;
return {buf.data(), static_cast<std::size_t>(len) };
}
}
/// @brief Parse file name info from full path
struct FilePathInfo {
std::string filepath_full; //!< full path with file name (the string input to parse)
std::string directory; //!< directory without file name
std::string filename; //!< filename without directory
std::string filename_base; //!< filename without directory and suffix after the last dot
std::string suffix; //!< the suffix after the last dot
static FilePathInfo parse(const std::string& filepath_full)
{
FilePathInfo info;
info.filepath_full = filepath_full;
auto p = filepath_full.find_last_of('/');
if (p == std::string::npos) {
info.directory = ".";
info.filename = filepath_full;
} else {
info.directory = filepath_full.substr(0, p);
info.filename = filepath_full.substr(p + 1);
}
if (info.directory.empty())
info.directory = "/";
p = info.filename.find_last_of('.');
if (p == std::string::npos) {
info.filename_base = info.filename;
info.suffix = "";
} else {
info.filename_base = info.filename.substr(0, p);
info.suffix = info.filename.substr(p + 1);
}
return info;
}
};
/// @brief Split string
std::vector<std::string> split(const std::string& s, const std::string& delimiter, bool remove_empty = true)
{
std::vector<std::string> ret;
size_t p0 = 0, p1;
auto delim_len = delimiter.size();
if (delim_len == 0)
return { s };
while ((p1 = s.find(delimiter, p0)) != std::string::npos) {
if (!remove_empty || p1 - p0 > 0)
ret.emplace_back(s.substr(p0, p1 - p0));
p0 = p1 + delim_len;
}
if (!remove_empty || p0 + 1 < s.size())
ret.emplace_back(s.substr(p0));
return ret;
}
/// @brief Split string
std::vector<std::string> split(const std::string& s, char delimiter, bool remove_empty = true)
{
std::vector<std::string> ret;
std::stringstream ss(s);
std::string item;
while (getline(ss, item, delimiter)) {
if (!remove_empty || !item.empty())
ret.emplace_back(item);
}
return ret;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment