關於這道題吧我本身沒什莫想法,在上網查閲一些資料後,勉强寫出來了,本篇主要是記錄自己學習過程遇到的問題,本文是轉載,原文在此:L1-064 估值一亿的AI核心代码 (20分)(Java正则表达式)_信小颜的博客-CSDN博客
上文給出了詳細的解釋。
import java.util.Scanner;
public class Main{
public static void main(String[]arge){
Scanner scan=new Scanner(System.in);
String str;
int n=Integer.parseInt(scan.nextLine());
for(int i=0;i<n;i++){
str=scan.nextLine();//整行輸入
System.out.println(str);//先原樣輸出
String cstr="";
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;
}
cstr+=chars[j];
}
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);
}
}
}
關於以上代碼中的這一処:
int n=Integer.parseInt(scan.nextLine());
不理解的話可以看看這篇文章:
Integer.parseInt(String s ,int radix)方法使用解释_qiezikuaichuan的专栏-CSDN博客
總結一下,這道題,我學習了正則表達式,Java的一些方法,以及做了一些關於正則表達式的練習,本次收穫還是不少啊,要多學習啊,都是我太菜了,😔。