C++ 读起含空格的字符串文件,截取指定长度字符串

 帮同学写的一个处理字符串程序。先从文件中读起包含大量空格的字符串(关键在于处理空格),再根据指定长度截取字符串。

#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

处理结果:

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值