C++用substr()函數消除前後空格

來源:互聯網
上載者:User

 最近做了個題目,遇到了要將字串前後空格消除的細節問題。在Java中好像有一個字串函數為trim()可以消除字串後的空格。對於c++,查了一下,可以引用一個c++標準庫Boost,可以輕鬆解決,但要下載,設定環境變數,因而沒去弄。當然還可以用Regex進行匹配,但似乎都大材小用。不如就用substr()函數,而且string有find_last_not_of,find_first_not_of等等屬性,已經夠我們解決問題了。

#include <iostream>
#include <vector>
#include <string>
#include <fstream>
using namespace std;
//從檔案中讀取每一行,然後消除前後空格,使其連成一個新的字串。
int main()
{
    string newstring = "";

    vector<string> str;
    ifstream fin("a.txt");
    string line;
    while (getline(fin, line))
        str.push_back(line);

    for (unsigned i = 0; i < str.size(); i++)
    {
        newstring += str[i].substr(str[i].find_first_not_of(" "),str[i].find_last_not_of(" ")-str[i].find_first_not_of(" ")+1);
    }
    cout<<newstring<<endl;
    return 0;
}

本文來自CSDN部落格,轉載請標明出處:http://blog.csdn.net/shuaiwang_01/archive/2008/11/01/3201560.aspx

聯繫我們

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