如何將字串前後的空白去除(C/C++) (STL)

來源:互聯網
上載者:User

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

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++程式員還是得熟析這種寫法。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.