strUtil.h
#pragma once
#include <cctype>
#include <vector>
#include <memory>
#include <sstream>
#include <type_traits>
#include <string_view>
#include <algorithm>
namespace cpv {
/** Return whether string starts with given pattern */
static inline bool startsWith(std::string_view str, std::string_view pattern) {
return (str.size() >= pattern.size() &&
str.substr(0, pattern.size()) == pattern);
}
/** Return whether string ends with given pattern */
static inline bool endsWith(std::string_view str, std::string_view pattern) {
return (str.size() >= pattern.size() &&
str.substr(str.size() - pattern.size()) == pattern);
}
/**
* Split string with specified characters.
* Call func(parts, count) while split.
* Default split characters are empty characters.
*/
template <class Func>
void splitString(
std::string_view str, const Func& func, const char* delimiter = " \t\r\n") {
std::size_t startIndex = 0;
std::size_t count = 0;
while (startIndex < str.size()) {
auto index = str.find_first_of(delimiter, startIndex);
auto endIndex = (index == str.npos) ? str.size() : index;
func(str.substr(startIndex, endIndex - startIndex), count);
index = str.find_first_not_of(delimiter, endIndex);
startIndex = (index == str.npos) ? str.size() : index;
++count;
}
}
/**
* Split string with specified characters.
* Call func(parts, count) while split.
* Single char version for better performance.
*/
template <class Func>
void splitString(std::string_view str, const Func& func, char delimiter) {
std::size_t startIndex = 0;
std::size_t count = 0;
while (startIndex < str.size()) {
auto index = str.find_first_of(delimiter, startIndex);
auto endIndex = (index == str.npos) ? str.size() : index;
func(str.substr(startIndex, endIndex - startIndex), count);
index = str.find_first_not_of(delimiter, endIndex);
startIndex = (index == str.npos) ? str.size() : index;
++count;
}
}
/**
* Join arguments into string.
* This function is very slow, don't call it where performance is important.
*/
template <class Delimiter, class... Args>
std::string joinString(Delimiter&a