C++中用substr()函數(shù)消除前后空格的解決方法詳解
更新時間:2013年05月21日 17:08:47 作者:
本篇文章是對C++中用substr()函數(shù)消除前后空格的方法進行了詳細的分析介紹,需要的朋友參考下
最近做了個題目,遇到了要將字符串前后空格消除的細節(jié)問題。在Java中好像有一個字符串函數(shù)為trim()可以消除字符串后的空格。對于c++,查了一下,可以引用一個c++標準庫Boost,可以輕松解決,但要下載,設置環(huán)境變量,因而沒去弄。當然還可以用正則表達式進行匹配,但似乎都大材小用。不如就用substr()函數(shù),而且string有find_last_not_of,find_first_not_of等等屬性,已經(jīng)夠我們解決問題了。
#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;
}
復制代碼 代碼如下:
#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;
}
相關(guān)文章
VSCode 使用 Code Runner 插件無法編譯運行文件名帶空格的文件問題
這篇文章主要介紹了VSCode 使用 Code Runner 插件無法編譯運行文件名帶空格的文件問題,本文通過圖文實例相結(jié)合給大家介紹的非常詳細,需要的朋友可以參考下2021-07-07
Pipes實現(xiàn)LeetCode(192.單詞頻率)
這篇文章主要介紹了Pipes實現(xiàn)LeetCode(192.單詞頻率),本篇文章通過簡要的案例,講解了該項技術(shù)的了解與使用,以下就是詳細內(nèi)容,需要的朋友可以參考下2021-08-08

