如何将字符串前后的空白去除(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行
for (c = s.begin(); c != s.end() && iswspace(*c++););
? s.erase(s.begin(), --c);
是將字符串前的whitespace刪除。
26和27行
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++程序員還是得熟析這種寫法。
轉載于:https://www.cnblogs.com/lzjsky/archive/2010/10/26/1861807.html
總結
以上是生活随笔為你收集整理的如何将字符串前后的空白去除(C/C++) (STL)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 360 与QQ 互掐 受害的却是用户
- 下一篇: c++是学习的关键