帮同学写的一个处理字符串程序。先从文件中读起包含大量空格的字符串(关键在于处理空格),再根据指定长度截取字符串。
#include<iostream.h>
#include<fstream.h>
#include<string.h>
#define strLength 100
struct node
{
char ch[10];//暂时将最大截取字符串限定在10个字符内
int chnumber;//记录字符个数
};
node strnode[strLength];//缓存截取的字符串
int nodeLength;//标记节点个数
bool Isame(char str[],int len)//判断截取的字符串是否出现过
{
str[len+1]='/0';
for(int i=0;i<nodeLength;i++)
{
if(!::strcmp(strnode[i].ch,str))//比较是否相同,返回比较结果
{
return false;
break;
}
}
return true;
}
void main()
{
int i=0,j=0,k=0;
nodeLength=0;
char filename[50];//存放文件名
cout<<"Please input the file path:";
cin>>filename;
ifstream in(filename);
in.seekg(0, ios::end); //设置文件指针到文件流的尾部
streampos ps = in.tellg(); //读取文件指针的位置
cout << "File size: " << ps << endl;
in.close(); //关闭文件流
ifstream myinf(filename);
int len;//需要截取的字符串长度
char str[strLength];//缓存从文件中读起字符串
//读起文件内容
myinf.read(str,ps);
myinf.close();//关闭文件流
str[ps+1]='/0';
for(i=0;i<ps;i++) //测试文件输出内容
cout<<str[i];
cout<<endl;
cout<<"Please input the length:";
cin>>len;
int allLength=ps;
int space=0;//标记空格数目
for(i=0;i<=(allLength/len);i++)
{
nodeLength++;
int len1=len;//标记截取字符串的末尾
::strcpy(strnode[i].ch,"");//初始化
strnode[i].chnumber=0;
for(j=0;j<len1;j++)
{
strnode[i].chnumber++;
if(str[i*len+j+space]!=0x20)//如果不是空字符,就写入结构体缓存
{
strnode[i].ch[j]=str[i*len+j+space];//????
}
else//如果是空格,跳过
{
allLength--;
space++;
//len1++;
strnode[i].ch[j]=str[i*len+j+space];
}
}
strnode[i].ch[strnode[i].chnumber]='/0';
}
//输出
bool bl;//标记字符串是否已经出现过
for(i=0;i<nodeLength;i++)
{
bl=Isame(strnode[i].ch,len);
if(!bl)
cout<<strnode[i].ch<<endl;
else
cout<<"SAME!"<<endl;
}
}
运行结果:
文件 d:/str.dat
内容:1 2 3 2 4 5 6 2 3 4 5 6 5 2 4
处理结果: