Introduction to Java Programming编程题9.2<检查子串>

本文介绍了一个简单的Java程序,用于检测一个字符串是否为另一个字符串的子串。通过用户输入两个字符串,程序判断第一个字符串是否包含于第二个字符串中,并给出相应的输出结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

书上要求用户输入两个字符串,检测第一个字符串是否是第二个字符串的子串,我的程序刚好相反。按书上的要求的话只要调用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;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值