一、题目
Problem #3018 - ECNU Online Judge
二、思路
①把w和s全部转换为小写,减少判断
②要在s中查找w且单词w必须与s中的某一独立单词在不区分大小写的情况下完全匹配,w仅是s中某一单词的一部分就不算匹配,则可分为两种情况:w在句首和不在句首,注意s首尾都可能有空格
③不在句首的话,w的前后至少有一个空格(最开始时:s+=" ",方便判断)
三、代码
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int t = scanner.nextInt();
scanner.nextLine();
for (int i = 0; i < t; i++) {
String w = scanner.nextLine();
String s = scanner.nextLine();
s = s.toUpperCase();
w = w.toUpperCase();
s += " ";//尾插一个空格,方便查找
System.out.println("case #" + i + ":");
if (s.startsWith(w+" ")) {//在句首
System.out.println(1);
} else if (s.contains(" " + w + " ")) {//其他位置
System.out.println(s.indexOf(" " + w + " ") + 2);//+2是因为起始位置为1且查找时多加了一个空格
} else {
System.out.println("None");
}
}
}
}