Abstract
在(原創) 如何將字串前後的空白去除? (使用string.find_first_not_of, string.find_last_not_of) (C/C++) (STL) 中已經可順利將字串前後的空白去除,且程式相當的精簡,在此用另外一種方式達到此要求,且可同時將whitespace去除,並且使用template寫法。
Introduction
原來版本的程式在VC8可執行,但無法在Dev-C++執行,目前已經修正。
stringTrim1.cpp / C++
1 /*
2 (C) OOMusou 2006 http://oomusou.cnblogs.com
3
4 Filename : StringTrim1.cpp
5 Compiler : Visual C++ 8.0 / Dev-C++ 4.9.9.2
6 Description : Demo how to trim string by find_first_not_of & find_last_not_of
7 Release : 07/15/2008
8 */
9 #include <string>
10 #include <iostream>
11 #include <cwctype>
12
13 using namespace std;
14
15 string& trim(string& s) {
16 if (s.empty()) {
17 return s;
18 }
19
20 string::iterator c;
21 // Erase whitespace before the string
22 for (c = s.begin(); c != s.end() && iswspace(*c++););
23 s.erase(s.begin(), --c);
24
25 // Erase whitespace after the string
26 for (c = s.end(); c != s.begin() && iswspace(*--c););
27 s.erase(++c, s.end());
28
29 return s;
30 }
31
32 int main( ) {
33 string s = " Hello World!! ";
34 cout << s << " size:" << s.size() << endl;
35 cout << trim(s) << " size:" << trim(s).size() << endl;
36 }
22和23行
// Erase whitespace before the string
for (c = s.begin(); c != s.end() && iswspace(*c++););
s.erase(s.begin(), --c);
是將字串前的whitespace刪除。
26和27行
// Erase whitespace after the string
for (c = s.end(); c != s.begin() && iswspace(*--c););
s.erase(++c, s.end());
是將字串後的whitespace刪除。
22行是一種變形的for寫法,for的expr3區沒寫,並將increment寫在expr2區,for從s.begin()開始,若未到s.end()尾端且是whitespace的話就繼續,並且判斷完whitespace就+1,其實整個for loop就相當於string.find_first_not_of(),要找到第一個不是whitespace的位置。
23行從s.begin()開始刪除whitespace,但為什麼要刪到--c呢?因為32行的for loop,在跳離for loop之前,已經先+1,所以在此要-1才會正確。
26和27行同理,只是它是從字串尾巴考慮。
我承認這段程式不是很好懂,是充滿了C style的寫法,不過++,--這種寫法本來就是C的光榮、C的特色,既然C++強調多典,又是繼承C語言,所以C++程式員還是得熟析這種寫法。
See Also
(原創) 如何將字串前後的空白去除? (使用string.find_first_not_of, string.find_last_not_of) (C/C++) (STL)
(原創) 如何將字串前後的空白去除? (C/C++) (boost)
Reference
C++ Cookbook Recipe 4.2