模拟题 HDU3052 VIM

http://acm.hdu.edu.cn/showproblem.php?pid=3052

题意:

  本题仅一组输入数据,第一行输入行数L,(L<=100)表示有一个包含L行文字的文本,接下来是L行文本,没行不超过100个字符,在文本之后是若干个替换命令,[range]s/{pattern}/{string}/[flag],命令中符号代表含义:

  :表示替换命令的开始;

  [range]表示被操作文本范围

  s是substitute的简写,是替换的意思;

  {pattern}和{string}是要匹配的文本和要替换的文本

  /用来做分隔符

  [flag]是一些操作的开关

本题重要规则及注意事项:

  (1)[range]一定会出现,“%”所有的行,或“a,b”(从a行到b行)

  (2){pattern}和{string}只包含字母,数字,空格和下划线。

  (3)命令分隔符包括/,~,!,@,#,$,%,^,&,*,(,),-,+,=。

  (4)[flag]只能是g

  (5)如果{pattern}为空,则使用上次不为空的{pattern}

  (6)如果{pattern}是{string}的子串,不进行递归替换

  (7)第i+1条命令处理的文本是由第i条命令处理后的文本。

 

题解:(模拟+string成员函数的使用)

1,先找[range]范围,找到起始和末尾行数。

2,通过找分隔符找出匹配和替换的内容。

3,替换内容,注意标记以输出 pattern not found 情况

 

Ps:

string str;

int find(char ch,int pos=0),从pos开始寻找字符ch所在位置

str.find(ch,pos);

int find(const char *s,int pos=0),从pos开始寻找字符串s所在位置

str.find(s,pos);

str.substr(pos,n);从pos开始截取长度为n的子串

string &replace(iterator first0, iterator last0,const char *s);//把[first0,last0)之间的部分替换为字符串s

string &replace(int p0, int n0,const char *s);//删除从p0开始的n0个字符,然后在p0处插入串s

str.replace(p0,n0,s);

 

代码:

#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include<string>
#include<iomanip>

using namespace std;
const int maxn=1e6+10;
typedef long long ll;

int n,sline,eline,pos_s,p1,p2,p3;
char separator;
string text[105],command;
string lastrepalce,repla,replaceby;
bool changed;

void reget(int &s,int &e,string str)
{
  int p=str.find(',');
  s=0;
  for(int i=0; i<p; i++)
  {
    s*=10;
    s+=str[i]-'0';
  }
  e=0;
  for(int i=p+1; i<str.length(); i++)
  {
    e*=10;
    e+=str[i]-'0';
  }
}

int main()
{
  cin>>n;
  cin.get();

  if(n==0) return 0;
  for(int i=1; i<=n; i++) getline(cin,text[i]);
  lastrepalce="";
  int flag=0;
  while (getline(cin,command))
  {
    if(flag) cout<<endl;
    flag=true;
    pos_s=command.find('s');
    if(pos_s==2){
      sline=1;
      eline=n;
    }
    else
    {
      reget(sline,eline,command.substr(1,pos_s-1));
    }

    separator=command[pos_s+1];
    p1=pos_s+1;
    p2=command.find(separator,p1+1);
    p3=command.find(separator,p2+1);
    repla=command.substr(p1+1,p2-p1-1);
    replaceby=command.substr(p2+1,p3-p2-1);

    if(repla=="") repla=lastrepalce;
    else lastrepalce=repla;
    changed=false;

    int re_len=repla.length(),reby_len=replaceby.length();
    for(int i=sline; i<=eline; i++)
    {
      bool c=0;
      int p=text[i].find(repla,0);
      while(p!=-1)
      {
        text[i].replace(p,re_len,replaceby);
        p=text[i].find(repla,p+reby_len);
        changed=true;
        c=1;
      }
      if(c) cout<<setw(4)<<i<<"  "<<text[i]<<endl;
    }
    if(!changed) cout<<"Pattern not found"<<endl;
  }
  system("pause");
  return 0;
}

 

posted on 2021-01-16 18:49  mmn  阅读(107)  评论(0编辑  收藏  举报