查找字符串中子字符串出现的位置(两种简单方法)

如:在在ABCDEJXBDHCJSBJXzh中查找JXB在哪个位置 

方法一:使用字符串的indexof()方法 。

时间复杂度:O(n * m),其中 n 是文本长度,m 是模式串长度。

空间复杂度:O(1)

public class Main {
    public static void main(String[] args) {
        String text = "ABCDEJXBDHCJSBJXzh";
        String pattern = "JXB";
        int index = text.indexOf(pattern);
        if (index != -1) {
            System.out.println("使用 indexOf() 方法找到匹配的字符串,位置在:" + index);
        } else {
            System.out.println("未找到匹配的字符串。");
        }
    }
}

方法二:正则表达式方法。

时间复杂度:通常情况下是 O(n),其中 n 是文本长度。

空间复杂度:O(1)或O(n)

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class A0 {
    public static void main(String[] args) {
        String text = "ABCDEJXBDHCJXBJXzhjxbjxbjxbJXBJXBJXB";
        String pattern = "JXB";
        Pattern p = Pattern.compile(pattern,Pattern.CASE_INSENSITIVE);
        Matcher m = p.matcher(text);
        if (m.find()) {
            System.out.println("使用正则表达式找到匹配的字符串,位置在:" + m.start()+"  "+m.end());
           String S= m.replaceAll("zzz");
            System.out.println(S);
        } else {
            System.out.println("未找到匹配的字符串。");
        }

    }
}

当然,还有许多好的方法,有兴趣的可以自己去学习以下。

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值