题目
(原题来自于网络)
泰兹瑞来到卡拉德许之后,由于他精湛的神器制造技术,可谓是过的如鱼得水。这次,他为自己打造了一个编辑器,称为威穆(Veim)。操作威穆时,有两种模式,具体操作如下。
在 Normal Mode 下
- 按下 i :进入 Insert Mode 。
- 按下 f :紧接着一个小写字母 char,若当前光标后(右)方有至少一个 char ,将光标移动到其所在位置,否则不移动。
- 按下 x :删除当前光标所在位的字符,后面的字符均会前移一格。
- 按下 h :将光标向左(前)移动一格,若无法移动就不移动。
- 按下 l :将光标向右(后)移动一格,若无法移动就不移动。
- 若按下了其他字符:无任何效果。
在 Insert Mode 下
- 按下非 e 小写字母 char :在光标当前位置前插入这个字母 char。
- 按下 e :退出 Insert Mode(进入 Normal Mode)。
具体请见样例。
现在泰兹瑞的威穆中已经写入了一个字符串 s 。接下去泰兹瑞进行了一波操作(按下了若干按键),他的按键序列为 t 。现给出 s 和 t ,求这波操作之后威穆内留下的字符串。
输入:两行,第一行字符串 s ,第二行字符串 t 。
输出: 一行,威穆里最后留下的字符串。
例如:
输入
applese
xfllhlia
输出
pplaese
题目说明
这个题目看上去有点难,但其实就是读题意coding。
这里主要用到了string的几个函数:
- 删除:s.erase()
- 插入:s.insert()
- 获取子字符串:s.substr()
这是笔试中最常用也是最容易忘记应该怎么用的两个函数。
string 删除
(1)erase(pos,n); 删除从pos开始的n个字符,比如erase(0,1)就是删除第一个字符
(2)erase(ite_position);删除ite_position处的一个字符(position是个string类型的迭代器)
(3)erase(ite_first, ite_last);删除从ite_first到ite_last之间的字符(first和last都是迭代器)
string 插入
(1)basic_string& insert (size_type pos, const basic_string& str);
在原串下标为pos的字符前插入字符串str
(2)basic_string& insert (size_type pos, const basic_string& str, size_type pos1, size_type n);
str从下标为pos1开始数的n个字符插在原串下标为pos的字符前
(3)basic_string& insert (size_type pos, size_type n, char c);
在原串下标为pos的字符前插入n个字符c
string 获取子字符串
(1)s.substr(pos, n) 截取s中从pos开始(包括0)的n个字符的子串,并返回
(2)s.substr(pos) 截取s中从从pos开始(包括0)到末尾的所有字符的子串,并返回
代码
#include<iostream>
#include<string>
using namespace std;
void input(string& s, string t, int &index, int &index_t)
{
// = 'e' 退出
if (t.empty() || t.size() < 0 || index >= s.size() || index < 0 )
return;
int kin = 0;
while (kin < t.size() && t[kin] != 'e')
{
//cout << "t[kin]" << t[kin] << endl;
s.insert(index++, 1, t[kin++]);
//cout << "s:" << s << endl;
}
index_t = index_t + kin;
}
void outString(string &s, string t)
{
int index = 0;
for(int i = 0; i < t.size() ; ++i)//&& !s.empty()
{
if (t[i] == 'i')
{
//cout << t[i] << "---" << s << " index:" << index << " i:" << i << endl;
string tt = t.substr(i + 1);
//cout << tt << endl;
input(s, tt, index, i);
//cout << t[i] << "---" << s << " index:" << index << " i:" << i << endl;
}
else if (t[i] == 'f' && i + 1 < t.size())
{
//cout << t[i] << "---" << s << " index:" << index << " i:" << i << endl;
for (int j = index+1; j < s.size(); ++j)
{
if (s[j] == t[i + 1])
{
index = j;
break;
}
}
++i;
//cout << t[i] << "---" << s << " index:" << index << " i:" << i << endl;
}
else if (t[i] == 'x')
{
s.erase(index, 1);
index = index < s.size() ? index : (s.size() - 1);
//cout << t[i] << "---" << s << " index:" << index << " i:" << i << endl;
}
else if (t[i] == 'h')
{
index = (index > 0) ? (index - 1) : 0;
//cout << t[i] << "---" << s << " index:" << index << " i:" << i << endl;
}
else if (t[i] == 'l')
{
index = (index < s.size() - 1) ? (index + 1) : (s.size() - 1);
//cout << t[i] << "---" << s << " index:" << index << " i:" << i << endl;
}
else
continue;
}
}
int main()
{
string s, t;
cin >> s;
cin >> t;
outString(s, t);
cout << s << endl;
return 0;
}