Trim / remove a tab ( "\t" ) from a string

hackingwords' answer gets you halfway there. But std::remove() from <algorithm> doesn't actually make the string any shorter -- it just returns an iterator saying "the new sequence would end here." You need to call my_string().erase() to do that:

#include <string>
#include <algorithm>    // For std::remove()

my_str.erase(std::remove(my_str.begin(), my_str.end(), '\t'), my_str.end());

The remove algorithm shifts all characters not to be deleted to the beginning, overwriting deleted characters but it doesn't modify the container's length (since it works on iterators and doesn't know the underlying container). To achieve this, call erase:

str.erase(remove(str.begin(), str.end(), '\t'), str.end());

If you want to remove all occurences in the string, then you can use the erase/remove idiom:

#include <algorithm>

s.erase(std::remove(s.begin(), s.end(), '\t'), s.end());

If you want to remove only the tab at the beginning and end of the string, you could use the boost string algorithms:

#include <boost/algorithm/string.hpp>

boost::trim(s); // removes all leading and trailing white spaces
boost::trim_if(s, boost::is_any_of("\t")); // removes only tabs

If using Boost is too much overhead, you can roll your own trim function using find_first_not_of and find_last_not_of string methods.

std::string::size_type begin = s.find_first_not_of("\t");
std::string::size_type end   = s.find_last_not_of("\t");

std::string trimmed = s.substr(begin, end-begin + 1);

Tags:

C++

String

Tabs