Java查找指定字符串第一次或最后一次出现的位置

本文介绍了一种用于查找字符串中子串出现位置的算法。该算法包括两个主要部分:一是获取首次匹配的索引,二是获取最后一次匹配的索引。通过将输入字符串转换为字符数组并逐个比较字符来实现。此外,提供了具体的实现代码及测试案例。

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

思路
1. 将输入的字符串转换为char 数组
2. 从第一个字符位置开始比较,并记录匹配的次数,如果匹配的次数等于查找字符串的长度就停止检索
3. 如果找不到匹配字符串的位置返回-1

/**
     * Returns the index within the given input string of the first occurrence
     * of the specified substring.
     * 
     * @param input
     * @param query
     */
    public static void getFirstMatchingIndex(String input, String query) {
        char[] inputChars = input.toCharArray();
        char[] queryChars = query.toCharArray();
        int inputLength = input.length();
        int queryLength = query.length();

        int inputIndex = 0;
        int queryIndex = 0;
        while (inputIndex < inputLength && queryIndex < queryLength) {
            if (inputChars[inputIndex] == queryChars[queryIndex]) {
                queryIndex++;
                inputIndex++;
            } else {
                inputIndex = inputIndex - queryIndex + 1;
                queryIndex = 0;
            }
        }

        int index = queryIndex == queryLength ? (queryLength > 1 ? inputIndex - queryLength : inputIndex - 1) : -1;
        System.out.println("first matching index:" + index);
    }

/**
     * Returns the index within this string of the rightmost occurrence of the 
     * specified substring.
     * 
     * @param input
     * @param query
     */
    public static void getLastMatchingIndex(String input, String query) {
        char[] inputChars = input.toCharArray();
        char[] queryChars = query.toCharArray();
        int inputLength = input.length();
        int queryLength = query.length();
        int inputIndex = inputLength - 1;
        int queryIndex = queryLength - 1;
        int matchingLenght = 0;
        while (inputIndex >= 0 && queryIndex >= 0) {
            if (inputChars[inputIndex] == queryChars[queryIndex]) {
                inputIndex--;
                queryIndex--;
                matchingLenght++;
            } else {
                inputIndex = matchingLenght <= 0 ? (inputIndex - 1) : inputIndex;
                queryIndex = queryLength - 1;
                matchingLenght = 0;
            }
            System.out.println("i:" + inputIndex + ",q:" + queryIndex);
        }
        System.out.println("last matching index:" + (matchingLenght == queryLength ? (inputIndex + 1) : -1));
    }

测试

getFirstMatchingIndex("ssssdeffsdfsdf", "sdf");
----->
first matching index:8



getFirstMatchingIndex("ssssdeffsdfsdf", "sdf");

--->



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值