• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
戈瑾
博客园    首页    新随笔    联系   管理    订阅  订阅
字符串查找判断

字符串查找判断

输入两个字符串s1和s2,判断s1是否包含s2,给出结论,若包含,还需计算s1中s2的个数。要求使用string类型

复制代码
import java.util.Scanner;
public class Study {
    public static void main(String[] args) {
        String str1, str2, str3;
        int m, n;
        int count = 0;
        Scanner in = new Scanner(System.in);
        System.out.print("请输入字符串s1:");
        str1 = in.nextLine();
        System.out.print("请输入字符串s2:");
        str2 = in.nextLine();
        // 判断字符串s1是否包含s2
        if ((str1.indexOf(str2)) != -1) {
            System.out.println("s1包含s2");
        } else {
            System.out.println("s1不包含s2");
        }
        m = str1.length();
        n = str2.length();
        // 判断s1中s2的个数
        for (int i = 0; i < m - n + 1; i++) {
            str3 = str1.substring(i, i + n);
            if (str3.equals(str2)) {
                count++;
            }
        }
        System.out.println("包含个数为:" + count);
    }
}
复制代码

posted on 2020-10-18 11:51  戈瑾  阅读(171)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3