本题要求你实现一个稍微更值钱一点的 AI 英文问答程序,规则是:
- 无论用户说什么,首先把对方说的话在一行中原样打印出来;
- 消除原文中多余空格:把相邻单词间的多个空格换成 1 个空格,把行首尾的空格全部删掉,把标点符号前面的空格删掉;
- 把原文中所有大写英文字母变成小写,除了
I
; - 把原文中所有独立的
can you
、could you
对应地换成I can
、I could
—— 这里“独立”是指被空格或标点符号分隔开的单词; - 把原文中所有独立的
I
和me
换成you
; - 把原文中所有的问号
?
换成惊叹号!
; - 在一行中输出替换后的句子作为 AI 的回答。
输入格式:
输入首先在第一行给出不超过 10 的正整数 N,随后 N 行,每行给出一句不超过 1000 个字符的、以回车结尾的用户的对话,对话为非空字符串,仅包括字母、数字、空格、可见的半角标点符号。
输出格式:
按题面要求输出,每个 AI 的回答前要加上 AI:
和一个空格。
输入样例:
6
Hello ?
Good to chat with you
can you speak Chinese?
Really?
Could you show me 5
What Is this prime? I,don 't know
输出样例:
Hello ?
AI: hello!
Good to chat with you
AI: good to chat with you
can you speak Chinese?
AI: I can speak chinese!
Really?
AI: really!
Could you show me 5
AI: I could show you 5
What Is this prime? I,don 't know
AI: what Is this prime! you,don't know
一.分析题意:
题目有bug
大小写换完,可以继续别的操作(这里因为“CAN YOU”这个样例自闭,一度只拿了15分)
但是如果把I换成you后,不能再进行can you/could you操作。
二.思路及代码
难点在于字符串的删除替换,有三种思路:
①vis标记,如果同时处理空格、替换can you/I,me要多重判断,会很难受。
扫描二维码关注公众号,回复:
6199383 查看本文章
②逆向思维,对字符串删除更换难,那不如把字符串分割为多个单词,再依次添加回去(一边输入一边处理)
(分割操作,string流做会简单)
③用STL string的方法做,就变成一道很简单的模拟
二三,难点只是判断多个空格
#include <bits/stdc++.h>
using namespace std;
int n;
bool ok(string a,int i,int p)//是否前后都是空格或标点,即独立
{
if(i-1>=0)
return !isalpha(a[i+p])&&!isdigit(a[i+p])&&!isalpha(a[i-1])&&!isdigit(a[i-1]);
else return !isalpha(a[i+p])&&!isdigit(a[i+p]);//防越界
}
int main()
{
cin>>n;
getchar();
while(n--)
{
string a;
getline(cin,a);
cout<<a<<endl;
int m=a.length();
for(int i=m-1;i>=0;i--)
{
if(i==m-1)
{
while(a[i]==' ')
{
a.erase(i,1);
i--;
}
break;
}
}
m=a.length();
for(int i=0;i<m;i++)//先把大写处理掉很关键,防止后面判断CAN YOU出不来
{
if(i==0)//开头空格
while(a[i]==' ')
a.erase(i,1);
while(a[i]==' ')//中间多余空格 ,这里要用while
if(!isalpha(a[i+1])&&!isdigit(a[i+1])&&i+1<m)
a.erase(i,1);
else break;
if(a[i]=='?')a[i]='!';
if(a[i]!='I'&&a[i]>='A'&&a[i]<='Z')
a[i]=a[i]-'A'+'a';
m=a.length();
}
for(int i=0;i<m;i++)
{
if(a.substr(i,2)=="me"&&ok(a,i,2)&&i+1<m) a.replace(i,2,"you");
else if(a[i]=='I'&&ok(a,i,1)) a.replace(i,1,"you");
else if(a.substr(i,7)=="can you"&&ok(a,i,7)&&i+6<m)a.replace(i,7,"I can");
else if(a.substr(i,9)=="could you"&&ok(a,i,9)&&i+8<m)a.replace(i,9,"I could");
m=a.length();//注意每次replace后,长度变了!
}
cout<<"AI: "<<a<<endl;
}
}
三. string 的用法
其中最好用的几个函数:
- 【】,push_back(),+=,==,size()/length()
- substr(index,num)获取index开始,长度为num的子串
- erase(index,num)删除index开始num个元素
- insert(index,a) index处插入a
- replace(index,num,a)从index开始num个元素替换为a字符串
- 3,4操作后string长度会改变!注意更新循环边界