create string::split with std::function

This commit is contained in:
Ken Van Hoeylandt 2025-08-18 22:27:54 +02:00
parent a2612d327a
commit 28f11a2cf3
2 changed files with 21 additions and 6 deletions

View File

@ -4,6 +4,7 @@
#include <cstdio> #include <cstdio>
#include <string> #include <string>
#include <vector> #include <vector>
#include <functional>
namespace tt::string { namespace tt::string {
@ -30,6 +31,16 @@ std::string getLastPathSegment(const std::string& path);
*/ */
std::vector<std::string> split(const std::string& input, const std::string& delimiter); std::vector<std::string> 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<void(const std::string&)> callback);
/** /**
* Join a set of tokens into a single string, given a delimiter (separator). * 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. * If the input is an empty list, the result will be an empty string.

View File

@ -29,24 +29,28 @@ std::string getLastPathSegment(const std::string& path) {
} }
} }
std::vector<std::string> split(const std::string&input, const std::string&delimiter) { void split(const std::string& input, const std::string& delimiter, std::function<void(const std::string&)> callback) {
size_t token_index = 0; size_t token_index = 0;
size_t delimiter_index; size_t delimiter_index;
const size_t delimiter_length = delimiter.length(); const size_t delimiter_length = delimiter.length();
std::string token;
std::vector<std::string> result;
while ((delimiter_index = input.find(delimiter, token_index)) != std::string::npos) { 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; token_index = delimiter_index + delimiter_length;
result.push_back(token); callback(token);
} }
auto end_token = input.substr(token_index); auto end_token = input.substr(token_index);
if (!end_token.empty()) { if (!end_token.empty()) {
result.push_back(end_token); callback(end_token);
} }
}
std::vector<std::string> split(const std::string&input, const std::string&delimiter) {
std::vector<std::string> result;
split(input, delimiter, [&result](const std::string& token) {
result.push_back(token);
});
return result; return result;
} }