Can anyone suggest a way of stripping tab characters ( "\t"s ) from a string? CString or std::string.
So that "1E10 " for example becomes "1E10".
Thanks in anticipation.
Can anyone suggest a way of stripping tab characters ( "\t"s ) from a string? CString or std::string.
So that "1E10 " for example becomes "1E10".
Thanks in anticipation.
First idea would be to use remove
remove(myString.begin(), myString.end(), "\t");
Though you might have to use remove_if instead if that comparison doesn't work.
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);
hackingwords' answer gets you halfway there. But 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 myString().erase()
to do that:
#include <string>
#include <algorithm> // For remove()
using namespace std;
myStr.erase(remove(myStr.begin(), myStr.end(), '\t'), myStr.end());
HackingWords is nearly there: Use erase in combination with remove.
std::string my_string = "this\tis\ta\ttabbed\tstring";
my_string.erase( std::remove( my_string.begin( ), my_string.end( ), my_string.end(), '\t') );
Since others already answered how to do this with std::string, here's what you can use for CString:
myString.TrimRight( '\t' ); // trims tabs from end of string
myString.Trim( '\t' ); // trims tabs from beginning and end of string
if you want to get rid of all tabs, even those inside the string, use
myString.Replace( _T("\t"), _T("") );