文字列からタブ文字 ( "\t"s ) を取り除く方法を提案できる人はいますか? CString または std::string。
たとえば、「1E10」は「1E10」になります。
文字列内のすべてのオカレンスを削除する場合は、 erase/removeイディオムを使用できます。
#include <algorithm>
s.erase(std::remove(s.begin(), s.end(), '\t'), s.end());
文字列の最初と最後のタブのみを削除する場合は、ブースト文字列アルゴリズムを使用できます。
#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
Boostの使用がオーバーヘッドが大きすぎる場合は、文字列メソッドを使用find_first_not_of
して独自のトリム関数をロールできます。find_last_not_of
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の答えはあなたを途中まで連れて行きます。ただしstd::remove()
、from<algorithm>
は実際には文字列を短くしません。つまり、「新しいシーケンスはここで終了します」というイテレータを返すだけです。あなたはそれをするために電話する必要がありますmy_string().erase()
:
#include <string>
#include <algorithm> // For std::remove()
my_str.erase(std::remove(my_str.begin(), my_str.end(), '\t'), my_str.end());
他の人が std::string でこれを行う方法をすでに回答しているため、CString に使用できるものは次のとおりです。
myString.TrimRight( '\t' ); // trims tabs from end of string
myString.Trim( '\t' ); // trims tabs from beginning and end of string
文字列内のタブを含め、すべてのタブを削除する場合は、次を使用します
myString.Replace( _T("\t"), _T("") );
HackingWordsはもうすぐそこにあります:eraseをremoveと組み合わせて使用します。
std::string my_string = "this\tis\ta\ttabbed\tstring";
my_string.erase( std::remove( my_string.begin(), my_string.end(), '\t'), my_string.end());
文字列をスキャンし、見つかったすべての出現箇所を削除します。
CString を置き換えますか?
置換 ('\t', '')
なぜ誰もこのように文字列をトリミングしないのだろうか:
void trim (string& s) {
string t = "";
int i = 0;
while(s[i] == ' ') i++;
while(s[i] == '\t') i++;
for(i; i < s.length(); i++)
t += s[i];
s = t;
}
最初のアイデアはremoveを使用することです
remove(myString.begin(), myString.end(), "\t");
その比較が機能しない場合は、代わりに remove_if を使用する必要があるかもしれませんが。