C++中用substr()函数消除前后空格的解决方法详解
更新时间:2013年05月21日 17:08:47 作者:
本篇文章是对C++中用substr()函数消除前后空格的方法进行了详细的分析介绍,需要的朋友参考下
最近做了个题目,遇到了要将字符串前后空格消除的细节问题。在Java中好像有一个字符串函数为trim()可以消除字符串后的空格。对于c++,查了一下,可以引用一个c++标准库Boost,可以轻松解决,但要下载,设置环境变量,因而没去弄。当然还可以用正则表达式进行匹配,但似乎都大材小用。不如就用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;
}
复制代码 代码如下:
#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;
}
相关文章
VSCode 使用 Code Runner 插件无法编译运行文件名带空格的文件问题
这篇文章主要介绍了VSCode 使用 Code Runner 插件无法编译运行文件名带空格的文件问题,本文通过图文实例相结合给大家介绍的非常详细,需要的朋友可以参考下2021-07-07


最新评论