除去文本文件每一行的空格
python:
rstrip()
删除字符串字符串末尾的空格.
lstrip()
截掉字符串左边的空格或指定字符。
strip([chars])
在字符串上执行 lstrip()和 rstrip()
files="conky.conf"
fin =open(files)
fout=open(files+'1','w')
for line in fin:
print (line)
fout.write(line.strip()+'\n')
cpp:
#include <ctype.h>
#include<iostream>
#include<fstream>
#include<string.h>
#define bufsize 300
using namespace std;
int main()
{
char buf[bufsize];
ifstream ifs("vimrc.txt",ifstream::in);
ofstream ofs("vimrc-.txt",ofstream::out);
if (ifs.is_open())
cout<<"open file successful"<<endl;
else{
cout<<"open file fail"<<endl;
return 1;
}
char *p=NULL;
int flag;
cout<<"if input 0, only remove space back of line. else remove front and back of line. "<<endl;
cin>>flag;
while(ifs.getline(buf,bufsize))
{
int len =strlen(buf);
while(isspace(buf[len-1]))
len--;
buf[len]='\0';
if(flag!=0)
{
len=0;
while(isspace(buf[len]))
len++;
p=buf+len;
cout<< p <<endl;
ofs<< p <<endl;
}
else
{
cout<<buf<<","<<strlen(buf)<<endl;
ofs<<buf<<endl;
}
}
ofs.close();
ifs.close();
return 0;
}
提取每一行第一个和最后一个字符串
/*************************************************************************
> File Name: str.cpp
> Author: ims
> Created Time: 2017/10/26 18:12:14
************************************************************************/
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
ifstream ifs("3ss.txt",ifstream::in);
char *p, first[100],buf[200];
int len=0;
while(ifs.getline(buf,200))
{
int tem=0;
len=strlen(buf);
while(isspace(buf[tem])&&tem<len)
tem++;
if(tem==len)
continue;
else
p=&buf[tem];
while(!isspace(buf[tem])&&tem<len)
tem++;
strcpy(first,p);
first[tem]='\0';
if(tem==len)
{
cout<<"1:only one str:"<<first<<endl;
continue;
}
while(isspace(buf[tem])&&tem<len)
tem++;
if(tem<len)
{
tem=len;
cout<< "src:"<<buf<<",len:"<< len <<endl;
while(isspace(buf[tem-1]))
tem--;
buf[tem]='\0';
while(!isspace(buf[tem-1]))
tem--;
p=&buf[tem];
cout<<"first str:"<< first <<endl;
cout<<"last str:"<<p<<endl;
}
else
cout<<"2:only one str:"<<first<<endl;
}
return 0;
}