【发布时间】:2014-02-16 21:55:56
【问题描述】:
我在大学时参加了微软编码挑战,这是被问到的问题:
编写一个程序,将两个字符串作为输入,一个是查询,另一个是可能包含也可能不包含该查询的字符串。您的程序需要查找查询是否包含在正文字符串中。
1) 只有在正文中匹配单词的开头时,查询才应该匹配正文。
2) 也就是说,查询的开头也必须是正文中单词的开头。例如,查询“cat”将匹配字符串“cat”、“cat toy”、“this is a cat”和“catty”。但是,查询“cat”与字符串“location”不匹配。
3) 你的程序应该不区分大小写。
4) 您的程序需要能够匹配其中没有空格的查询,即使正文中确实有空格。例如,字符串“Luke Johnston”将与查询“luke j”和查询“lukej”相匹配。
5) 但是,反过来就不行了。查询“luke j”不应匹配字符串“lukejohnston”。
我能够编写满足前 4 个要求的代码,但我无法找到第 5 个要求的解决方案。任何提示/帮助表示赞赏。这是我的代码版本。
package regex;
import java.util.Scanner;
public class TextQueryMatch {
public static void main(String[] args){
Scanner in = new Scanner(System.in);
System.out.print("Enter the Text: ");
String text = in.nextLine();
text = text.toLowerCase();
String[] substexts = text.split("\\s");
text = "";
for(int i = 0; i < substexts.length; i++){
char capLetter = Character.toUpperCase(substexts[i].charAt(0));
text += capLetter + substexts[i].substring(1, substexts[i].length());
}
System.out.println(text);
System.out.print("Enter the Query: ");
String query = in.nextLine();
query = query.toLowerCase();
String[] subquerys = query.split("\\s");
query = "";
for(int i = 0; i < subquerys.length; i++){
char capLetter = Character.toUpperCase(subquerys[i].charAt(0));
query += capLetter + subquerys[i].substring(1, subquerys[i].length());
}
System.out.println(query);
System.out.print("Match: ");
if(text.matches("(.*)"+query.charAt(0)+"(.*)")){
text=text.toLowerCase();
query=query.toLowerCase();
System.out.print(text.matches("(.*)"+query+"(.*)"));
}else{
System.out.print("False");
}
}
}
【问题讨论】: