(原創) 如何將字串前後的空白去除? (使用string.find_first_not_of, string.find_last_not_of) (C/C++)

來源:互聯網
上載者:User

這在字串處理是很常用的功能,.NET Framework的String class直接提供Trim()的method,其它語言也大都有提供(VB、VFP),但C++無論Standard Library或STL都找不到相對應方法,以下的方式是由希冀blog中的C++中如何去掉std::string對象的首尾空格 改編而來,加上了pass by reference適合function使用,其中std::string所提供的find_first_not_of()和find_last_not_of()真是大開眼界,竟然還有這種method,可以找尋第一個不合格位置,我在其它語言都還沒見過這樣的function。

 1/**//* 
 2(C) OOMusou 2006 http://oomusou.cnblogs.com
 3
 4Filename    : StringTrim1.cpp
 5Compiler    : Visual C++ 8.0
 6Description : Demo how to trim string by find_first_not_of & find_last_not_of
 7Release     : 11/17/2006
 8*/
 9#include <iostream>
10#include <string>
11
12std::string& trim(std::string &);
13
14int main() {
15  std::string s = "   Hello World!!   ";
16  std::cout << s << " size:" << s.size() << std::endl;
17  std::cout << trim(s) << " size:" << trim(s).size() << std::endl;
18
19  return 0;
20}
21
22std::string& trim(std::string &s) {
23  if (s.empty()) {
24    return s;
25  }
26
27  s.erase(0,s.find_first_not_of(" "));
28  s.erase(s.find_last_not_of(" ") + 1);
29  return s;
30}
31

See Also
(原創) 如何將字串前後的空白去除? (使用template,可去whitespace) (C/C++) (template)
(原創) 如何將字串前後的空白去除? (C++) (boost)

Reference
C++中如何去掉std::string對象的首尾空格

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.