集册 Java实例教程 在字符串中搜索模式,返回所有偏移索引

在字符串中搜索模式,返回所有偏移索引

欢马劈雪     最近更新时间:2020-01-02 10:19:05

440
提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
在字符串中搜索模式,返回所有偏移索引

class Main

{

    public static void search(String text, String pattern)

    {//时 代 J a v a - nowjava.com

        int lengthText = text.length();

        int lengthPattern = pattern.length();


        for(int i = 0; i <= lengthText - lengthPattern; i++)

        {

            int j;


            for(j = 0; j < lengthPattern; j++)

                if(text.charAt(i + j) != pattern.charAt(j))

                    break;


            if(j == lengthPattern)

               System.out.println("Pattern found at " + (i + 1));

        }

    }


    public static void main(String[] args)

    {
    /* from 
    NowJava.com
展开阅读全文