L1-064 估值一亿的AI核心代码 (stringstream消除空格)

在这里插入图片描述

以上图片来自新浪微博。

在这里插入图片描述

输出格式:
按题面要求输出,每个 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

关键在于用stringstream切块,以及在进行替换时for循环中对不同情况的处理
也就是把一个长句切成一个个单词,存到字符串数组里面

#include <iostream>
#include <stdio.h>
#include <string.h>
#include<bits/stdc++.h>
using namespace std;


bool ismark(char ch)
{
	return (!isalnum(ch) && ch!=' ');
}
// 只有四种字符, 字母 数字 空格 标点符号 
int main()
{
	string s,temp,res,word[1001];
	int n;cin>>n;getchar();
	while(n--)
	{	
	getline(cin, s);//pta不能用gets
	res+=s+"\nAI:";
    for(int i=0;i<s.size();i++){
            if(isalnum(s[i])){  //isalnum(),字母或数字
                if(s[i]!='I')
                    s[i]=tolower(s[i]);  //tolower()
            }
			else{
                //分割成一块一块的
                s.insert(i," ");  //s.insert()
                 i++;
            }
            if(s[i]=='?')
                s[i]='!';
        }
	
	stringstream ss(s);
	int cnt=0;
	while(ss>>temp)
	{
		word[cnt++]=temp;
		//cout<<temp<<endl;
	}//分割
	
	if(ismark(word[0][0]))res+=" ";
	
	 for(int i=0;i<cnt;i++)
	 {
	 	if(word[i]=="I" || word[i]=="me" )res+=" you";
	 	
	 	else if(word[i]=="can" && word[i+1]=="you" && i+1<cnt)
	 	{res+=" I can"; i++; continue;}
	 	else if(word[i]=="could" && word[i+1]=="you" && i+1<cnt)
	 	{ res+=" I could"; i++; continue;}
	 	
	 	else if(ismark(word[i][0]))res+=word[i];
	 	
	 	else res+=" "+word[i];

	 }
	 res+='\n';
	}
	 
	 cout<<res;
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值