From 9955efca718d8be72b63c7c2182ca59e7b9d0935 Mon Sep 17 00:00:00 2001 From: Mikko Rasa Date: Thu, 4 Mar 2021 12:26:25 +0200 Subject: [PATCH] Add some utility functions for joining strings --- source/strings/utils.cpp | 14 ++++++++++++++ source/strings/utils.h | 12 +++++++----- 2 files changed, 21 insertions(+), 5 deletions(-) diff --git a/source/strings/utils.cpp b/source/strings/utils.cpp index 416188e..80e59f0 100644 --- a/source/strings/utils.cpp +++ b/source/strings/utils.cpp @@ -130,6 +130,20 @@ string strip(const string &s) return result; } +string &append(string &str, const string &sep, const string &other) +{ + if(!str.empty() && !other.empty()) + str += sep; + str += other; + return str; +} + +string join(const string &str1, const string &sep, const string &str2) +{ + string result = str1; + return append(result, sep, str2); +} + string c_unescape(const std::string &str) { bool escape = false; diff --git a/source/strings/utils.h b/source/strings/utils.h index 2040bcd..f7e9433 100644 --- a/source/strings/utils.h +++ b/source/strings/utils.h @@ -56,17 +56,19 @@ std::vector split_fields(const std::string &str, const std::string separators will cause an empty string to be placed in the result. */ std::vector split_fields(const std::string &str, char sep, int max_split = -1); +/** Appends a string to another, using a separator if both are non-empty. */ +std::string &append(std::string &str, const std::string &sep, const std::string &other); + +/** Joins two strings, using a separator if both are non-empty. */ +std::string join(const std::string &str1, const std::string &sep, const std::string &str2); + /** Concatenates strings from an iterator range. */ template std::string join(Iter begin, Iter end, const std::string &sep = " ") { std::string result; for(Iter i=begin; i!=end; ++i) - { - if(i!=begin) - result += sep; - result += *i; - } + append(result, sep, *i); return result; } -- 2.45.2