Skip to content

Instantly share code, notes, and snippets.

@mattearly
Created April 16, 2017 00:35
Show Gist options
  • Save mattearly/ef81908f534f4069c2a3ec9b50994c0b to your computer and use it in GitHub Desktop.
Save mattearly/ef81908f534f4069c2a3ec9b50994c0b to your computer and use it in GitHub Desktop.
python-like trim for c++
#pragma once
#include <string>
//because other langauges have these and the c++ does not
//Trims whitespace - from http://stackoverflow.com/questions/1798112/removing-leading-and-trailing-spaces-from-a-string
std::string trim(const std::string& str,
const std::string& whitespace = " \t")
{
const auto strBegin = str.find_first_not_of(whitespace);
if (strBegin == std::string::npos)
return ""; // no content
const auto strEnd = str.find_last_not_of(whitespace);
const auto strRange = strEnd - strBegin + 1;
return str.substr(strBegin, strRange);
}
//Reduces whitespace - from http://stackoverflow.com/questions/1798112/removing-leading-and-trailing-spaces-from-a-string
std::string reduce(const std::string& str,
const std::string& fill = " ",
const std::string& whitespace = " \t")
{
// trim first
auto result = trim(str, whitespace);
// replace sub ranges
auto beginSpace = result.find_first_of(whitespace);
while (beginSpace != std::string::npos)
{
const auto endSpace = result.find_first_not_of(whitespace, beginSpace);
const auto range = endSpace - beginSpace;
result.replace(beginSpace, range, fill);
const auto newStart = beginSpace + fill.length();
beginSpace = result.find_first_of(whitespace, newStart);
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment