(原創) 如何将字符串前后的空白去除? (C/C++) (STL)

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

posted on 2008-07-15 21:00  真 OO无双  阅读(4703)  评论(2编辑  收藏  举报

导航