Java:字符串2在字符串1中第一次出现时的位置,不出现则返回-1。

public class TestSearchIndex {
    public static void main(String[] args) {
        String one = "小笼包子";
        String two = "包";
        System.out.println("方法1:" + searchIndex(one, two));   //方法1:2
        System.out.println("方法2:" + searchIndex2(one, two));  //方法2:2
    }
    //方法1
    static int searchIndex(String one, String two) {
        Matcher matcher = Pattern.compile(two).matcher(one);
    /*  if (matcher.find()) {
            return matcher.start();
        } else {
            return -1;
        }
    */
     return matcher.find()?matcher.start():-1;
    }
    //方法2
    static int searchIndex2(String one, String two) {
        return one.indexOf(two);
    }
}
posted @ 2020-09-03 16:20  卢肥  阅读(257)  评论(0)    收藏  举报