日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > c/c++ >内容正文

c/c++

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

發(fā)布時間:2025/7/25 c/c++ 23 豆豆
生活随笔 收集整理的這篇文章主要介紹了 如何将字符串前后的空白去除(C/C++) (STL) 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

Abstract
在(原創(chuàng)) 如何將字符串前后的空白去除? (使用string.find_first_not_of, string.find_last_not_of) (C/C++) (STL) 中已經(jīng)可順利將字符串前后的空白去除,且程序相當?shù)木?#xff0c;在此用另外一種方式達到此要求,且可同時將whitespace去除,并且使用template寫法。

Introduction
原來版本的程式在VC8可執(zhí)行,但無法在Dev-C++執(zhí)行,目前已經(jīng)修正。

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區(qū)沒寫,并將increment寫在expr2區(qū),for從s.begin()開始,若未到s.end()尾端且是whitespace的話就繼續(xù),并且判斷完whitespace就+1,其實整個for loop就相當于string.find_first_not_of(),要找到第一個不是whitespace的位置。

23行從s.begin()開始刪除whitespace,但為什么要刪到--c呢?因為32行的for loop,在跳離for loop之前,已經(jīng)先+1,所以在此要-1才會正確。

26和27行同理,只是它是從字符串尾巴考慮。

我承認這段程序不是很好懂,是充滿了C style的寫法,不過++,--這種寫法本來就是C的光榮、C的特色,既然C++強調(diào)多典,又是繼承C語言,所以C++程序員還是得熟析這種寫法。

轉(zhuǎn)載于:https://www.cnblogs.com/lzjsky/archive/2010/10/26/1861807.html

總結

以上是生活随笔為你收集整理的如何将字符串前后的空白去除(C/C++) (STL)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。