去除string字串中的空格

2021-05-25 10:49:08 字數 1758 閱讀 4823

很多其他語言的libary都會有去除string類的首尾空格的庫函式,但是標準c++的庫卻不提供這個功能。但是c++string也提供很強大的功能,實現trim這種功能也不難。下面是幾種方法:

1.使用string的find_first_not_of,和find_last_not_of方法

/* 

filename : stringtrim1.cpp

compiler : visual c++ 8.0

description : demo how to trim string by find_first_not_of & find_last_not_of

release : 11/17/2006

*/ #include #include std::string& trim(std::string &);

int main()

std::string& trim(std::string &s)

s.erase(0,s.find_first_not_of(" "));

s.erase(s.find_last_not_of(" ") + 1);

return s;

}

2.使用boost庫中的trim,boost庫對提供很多c++標準庫沒有但是又非常常用和好用的庫函式,例如正規表示式,執行緒庫等等。

/* 

filename : booststringtrim.cpp

compiler : visual c++ 8.0 / iso c++ (boost)

description : demo how to boost to trim string

release : 02/22/2007 1.0 */

#include #include #include using namespace std;

using namespace boost;

int main()

3.使用template(我用gcc編譯不通過,用vs2005卻可以)

/* 

filename : stringtrim1.cpp

compiler : visual c++ 8.0 description :

demo how to trim string by other method.

release : 11/18/2006

*/ #include #include #include template std::basic_string& trim(std::basic_string&);

int main( )

template std::basic_string& trim(std::basic_string& s)

std::basic_string::iterator c;

// erase whitespace before the string

for (c = s.begin(); c != s.end() && iswspace(*c++););

s.erase(s.begin(), --c);

// erase whitespace after the string

for (c = s.end(); c != s.begin() && iswspace(*--c);); s.erase(++c, s.end());

return s;

}

去除字串中的空格

使用js去除字串內所帶有空格,有以下三種方法 1 replace正則匹配方法 去除字串內所有的空格 str str.replace s g,去除字串內兩頭的空格 str str.replace s s g,去除字串內左側的空格 str str.replace s 去除字串內右側的空格 str str...

去除字串中的空格

利用迭代的思想將字串中的空字元去除 去除字串中的所有空格 deftrim s index 0while index len s if s index if index 0 如果是首字母是空格,直接向後推一位進行迭代 return trim s index 1 len s if index len s...

Java去除字串中的空格

strim或者trip都是只能去除頭部和尾部的空字串。中間的部分是不能夠去除的 推薦使用apachecommonse的stringutils.deletewhitespace a b c 刪除所有空格。如果我自己寫,我會採用foreache遍歷每乙個字串中的字元然後利用stringbuilder追加...