With string_view, stripping whitespace can be done without allocs.

This commit is contained in:
Henrik Rydgård committed 2023-09-26 13:19:19 +02:00
1 parent 20e703db83
commit 2bd2292bac
4 files changed
+47 -20

No files matched your search

+21 -5
View File
@@ -239,18 +239,15 @@ std::string StringFromFormat(const char* format, ...)
return temp;
}
std::string StringFromInt(int value)
{
std::string StringFromInt(int value) {
char temp[16];
snprintf(temp, sizeof(temp), "%d", value);
return temp;
}
// Turns " hej " into "hej". Also handles tabs.
std::string StripSpaces(const std::string &str)
{
std::string StripSpaces(const std::string &str) {
const size_t s = str.find_first_not_of(" \t\r\n");
if (str.npos != s)
return str.substr(s, str.find_last_not_of(" \t\r\n") - s + 1);
else
@@ -268,6 +265,25 @@ std::string StripQuotes(const std::string& s)
return s;
}
// Turns " hej " into "hej". Also handles tabs.
std::string_view StripSpaces(std::string_view str) {
const size_t s = str.find_first_not_of(" \t\r\n");
if (str.npos != s)
return str.substr(s, str.find_last_not_of(" \t\r\n") - s + 1);
else
return "";
}
// "\"hello\"" is turned to "hello"
// This one assumes that the string has already been space stripped in both
// ends, as done by StripSpaces above, for example.
std::string_view StripQuotes(std::string_view s) {
if (s.size() && '\"' == s[0] && '\"' == *s.rbegin())
return s.substr(1, s.size() - 2);
else
return s;
}
void SplitString(const std::string& str, const char delim, std::vector<std::string>& output)
{
size_t next = 0;