From 28f11a2cf3ebb80d48400371f0df19d8aec321be Mon Sep 17 00:00:00 2001 From: Ken Van Hoeylandt Date: Mon, 18 Aug 2025 22:27:54 +0200 Subject: [PATCH] create string::split with std::function --- TactilityCore/Include/Tactility/StringUtils.h | 11 +++++++++++ TactilityCore/Source/StringUtils.cpp | 16 ++++++++++------ 2 files changed, 21 insertions(+), 6 deletions(-) diff --git a/TactilityCore/Include/Tactility/StringUtils.h b/TactilityCore/Include/Tactility/StringUtils.h index b92c3196..5ad0713a 100644 --- a/TactilityCore/Include/Tactility/StringUtils.h +++ b/TactilityCore/Include/Tactility/StringUtils.h @@ -4,6 +4,7 @@ #include #include #include +#include namespace tt::string { @@ -30,6 +31,16 @@ std::string getLastPathSegment(const std::string& path); */ std::vector split(const std::string& input, const std::string& delimiter); +/** + * Splits the provided input into separate pieces with delimiter as separator text. + * When the input string is empty, the output list will be empty too. + * + * @param input the input to split up + * @param delimiter a non-empty string to recognize as separator + * @param callback the callback function that receives the split parts + */ +void split(const std::string& input, const std::string& delimiter, std::function callback); + /** * Join a set of tokens into a single string, given a delimiter (separator). * If the input is an empty list, the result will be an empty string. diff --git a/TactilityCore/Source/StringUtils.cpp b/TactilityCore/Source/StringUtils.cpp index e7f8969f..43afa563 100644 --- a/TactilityCore/Source/StringUtils.cpp +++ b/TactilityCore/Source/StringUtils.cpp @@ -29,24 +29,28 @@ std::string getLastPathSegment(const std::string& path) { } } -std::vector split(const std::string&input, const std::string&delimiter) { +void split(const std::string& input, const std::string& delimiter, std::function callback) { size_t token_index = 0; size_t delimiter_index; const size_t delimiter_length = delimiter.length(); - std::string token; - std::vector result; while ((delimiter_index = input.find(delimiter, token_index)) != std::string::npos) { - token = input.substr(token_index, delimiter_index - token_index); + std::string token = input.substr(token_index, delimiter_index - token_index); token_index = delimiter_index + delimiter_length; - result.push_back(token); + callback(token); } auto end_token = input.substr(token_index); if (!end_token.empty()) { - result.push_back(end_token); + callback(end_token); } +} +std::vector split(const std::string&input, const std::string&delimiter) { + std::vector result; + split(input, delimiter, [&result](const std::string& token) { + result.push_back(token); + }); return result; }