以上图片来自新浪微博。
本题要求你实现一个稍微更值钱一点的 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
读取输入:
原样输出每行输入:
大小写转换:
处理空格和标点:
替换特定单词和标点:
输出处理后的字符串:
逃得了敲笨钟跑不了这题,要牢记字符串处理这类型题目的所有API以及正则表达式
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) {
int n = Integer.parseInt(reader.readLine());
for (int i = 0; i < n; i++) {
String str = reader.readLine(); // 读取整行
System.out.println(str); // 原样输出
// 将所有大写字母转换为小写,除了'I'
char[] chars = str.toCharArray();
for (int j = 0; j < chars.length; j++) {
if (chars[j] >= 'A' && chars[j] <= 'Z' && chars[j] != 'I') {
chars[j] += 32;
}
}
String cstr = new String(chars);
// 空格和标点处理
cstr = cstr.trim(); // 去掉首尾空格
cstr = cstr.replaceAll(" +", " "); // 相邻单词间的多个空格换成一个空格
cstr = cstr.replaceAll(" (\\W)", "$1"); // 标点符号前的空格处理
// 替换特定单词和标点
cstr = cstr.replaceAll("\\?", "!");
cstr = cstr.replaceAll("\\bcan you\\b", "A");
cstr = cstr.replaceAll("\\bcould you\\b", "B");
cstr = cstr.replaceAll("\\b(I|me)\\b", "C");
cstr = cstr.replaceAll("A", "I can");
cstr = cstr.replaceAll("B", "I could");
cstr = cstr.replaceAll("C", "you");
System.out.println("AI: " + cstr);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}