Donnerstag, 2. Februar 2012

C++: String trim function

This function removes leading and trailing characters from a string. The default character is a space, but you can use any combination of characters, that should be trimmed.

std::string trim(std::string &str, const std::string &trimChars = " ")
{
  std::string result = str.erase(str.find_last_not_of(trimChars) + 1);
  return result.erase(0, result.find_first_not_of(trimChars));
}

Usage:
string s = trim("Hello World!    ");
std::cout << s;
// prints: Hello World!

s = trim("xxx Hello World! xxx", "x");
std::cout << s;
// prints: Hello World!

Keine Kommentare:

Kommentar veröffentlichen