From 1ec7201558db4203d57d499d97b97d3df0f07c19 Mon Sep 17 00:00:00 2001 From: Matthew Woehlke Date: Mon, 1 Dec 2025 12:31:24 -0500 Subject: [PATCH] cmStringAlgorithms: Add cmStripWhitespace Add a utility function to strip whitespace from a `string_view`. This is identical to the existing `cmTrimWhitespace`, but does not allocate a new `string`, instead returning the result as another `string_view`. --- Source/cmStringAlgorithms.cxx | 18 ++++++++++++++++++ Source/cmStringAlgorithms.h | 6 ++++++ 2 files changed, 24 insertions(+) diff --git a/Source/cmStringAlgorithms.cxx b/Source/cmStringAlgorithms.cxx index df3b7d9c6d..544d7160c1 100644 --- a/Source/cmStringAlgorithms.cxx +++ b/Source/cmStringAlgorithms.cxx @@ -38,6 +38,24 @@ std::string cmTrimWhitespace(cm::string_view str) return std::string(start, stop + 1); } +cm::string_view cmStripWhitespace(cm::string_view str) +{ + std::string::size_type const l = str.size(); + + std::string::size_type s = 0; + while (s < l && cmIsSpace(str[s])) { + ++s; + } + if (s == l) { + return cm::string_view{}; + } + std::string::size_type e = l - 1; + while (cmIsSpace(str[e])) { + --e; + } + return str.substr(s, e + 1 - s); +} + std::string cmRemoveQuotes(cm::string_view str) { // We process only strings that have two quotes at least. diff --git a/Source/cmStringAlgorithms.h b/Source/cmStringAlgorithms.h index b0d01c00ba..d847ece5bd 100644 --- a/Source/cmStringAlgorithms.h +++ b/Source/cmStringAlgorithms.h @@ -62,6 +62,12 @@ inline bool cmIsSpace(char ch) /** Returns a string that has whitespace removed from the start and the end. */ std::string cmTrimWhitespace(cm::string_view str); +/** + * Returns a string view that has whitespace removed from the start and the + * end. + */ +cm::string_view cmStripWhitespace(cm::string_view str); + /** Returns a string that has quotes removed from the start and the end. */ std::string cmRemoveQuotes(cm::string_view str);