题目不难,主要注意两点:
- \s 之后只有数字和 '.' 属于转义部分,而且 '.' 最多有一个,其它的字符和当前的 \s 无关;
- 任意字符都可能是最后一个字符,要随时判断下一个字符是否为 EOF。
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
int main()
{
string s; //最终输出的字符串
bool flag = true; //是否为转义状态
char c, pre = EOF; //当前字符,前一个字符
while ((c = getchar()) != EOF)
{
if (flag)
{
if (pre == '\\' && c == 's') //'\s'
{
bool hasPoint = false; //当前的'\s'之后是否出现过'.'
while ((c = getchar()) != EOF)
{
if (!hasPoint && c == '.') //第一次出现'.'
{
hasPoint = true;
continue;
}
if (!isdigit(c) || (hasPoint && c == '.'))
break;
}
if (c == EOF)
break;
}
else if (pre == '\\' && c == 'b') //'\b'
{
if ((c = getchar()) == EOF)
break;
}
else if (pre == '\\' && c == 'i') //'\i'
{
if ((c = getchar()) == EOF)
break;
}
else if (pre == '\\' && c == '*') //'\*'
{
flag = false;
if ((c = getchar()) == EOF)
break;
}
else if (pre == '\\')
{
s += c;
if ((c = getchar()) == EOF)
break;
}
else
{
if (pre != EOF)
s += pre;
}
}
else
{
if (pre == '\\' && c == '*')
{
flag = true;
if ((c = getchar()) == EOF)
break;
}
else
{
if(pre != EOF)
s += pre;
}
}
pre = c; //当前字符赋值给前一个字符,继续向后读取
}
if (pre != EOF)
{
s += pre;
}
cout << s;
return 0;
}
继续加油。