1. 程式人生 > >兩個字串A,B,求B在A中首次出現的位置,如果B不在A中返回-1.

兩個字串A,B,求B在A中首次出現的位置,如果B不在A中返回-1.

package paixu;
import java.util.*;
/**
 * Created by Administrator on 2017/9/17.
 */
public class PIpei {
    public static void main(String[] args){
        Scanner in = new Scanner(System.in);
        while(in.hasNext()){
            String str1=in.nextLine();
String str2 =in.nextLine();
pipei(str1,str2);
} } public static int pipei(String str1,String str2) { int len1 = str1.length(); int len2 = str2.length(); int i = 0; int j = 0; while (i < len1 && j < len2) { if (str1.charAt(i) == str2.charAt(j)) { i++; j++; } else
{ i = i - j + 1; j = 0; } if (j == len2) { System.out.println(i - j + 1); } } return -1;} }