书上要求用户输入两个字符串,检测第一个字符串是否是第二个字符串的子串,我的程序刚好相反。按书上的要求的话只要调用isSubstring(str1, str2)时改为isSubstring(str2, str1)即可。
/*
Enter the first String: Merry chrismas Mr.Lawrence
Enter the Second String: Mr.Lawrence
"Merry chrismas Mr.Lawrence" have "Mr.Lawrence"
Enter the first String: a thousand kisses deep
Enter the Second String: nice
"a thousand kisses deep" don't have "nice"
*/
import java.util.Scanner;
public class IsSubString {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the first String: ");
String str1 = input.nextLine();
System.out.print("Enter the Second String: ");
String str2 = input.nextLine();
if (isSubstring(str1, str2))
System.out.println("\"" + str1 + "\"" + " have " + "\"" + str2 + "\"");
else
System.out.println("\"" + str1 + "\"" + " don't have " + "\"" + str2 + "\"");
}
public static boolean isSubstring(String str1, String str2) {
if (str1.length() < str2.length())
return false;
int i, j = 0;
for (i = 0; i < str1.length(); i++) {
for (j = 0; j < str2.length(); j++) {
if (str2.charAt(j) != str1.charAt(i))
break;
else
i++;
}
}
if (j == str2.length())
return true;
else
return false;
}
}