手写实现indexOf

突然奇想。自己手写一个indexOf

package com.toov5.test;

public class Test8 {

    public static int find(String str1, String str2) {
        
        char[] str1Arr  = str1.toCharArray();
        char[] str2Arr = str2.toCharArray();
        
        int str1Length = str1.length();
        int str2Length = str2.length();
        
        int str1Index = 0;
        int str2Index = 0;
        
        while ( (str1Index < str1Length) && (str2Index < str2Length)) {
            if (str1Arr[str1Index] == str2Arr[str2Index]) {
                str1Index++;
                str2Index++;
            }else {
                str1Index = str1Index -str2Index +1;
                str2Index = 0;
            }
            
        }
        
        int index = str2Length == str2Length ? (str2Length > 1 ? str1Index - str2Index : str2Index -1 ) :  -1;
        return index;
        
    }
    
    
}

 

易读性的,练练代码能力:

package com.toov5.test;

public class TestOk1 {
  
    public static int getIndex(String str1 ,String str2) {
         
    String    LonggerStr = str1.length() > str2.length() ? str1 : str2;
    String  ShorterStr = str1.length() > str2.length() ? str2 : str1;    
    int mark = 0; //标记位置  
    
    for(int i=0 ; i< LonggerStr.length(); i++) {
         if (LonggerStr.charAt(i) == ShorterStr.charAt(0)) {
             mark = i;
             int index = i;
             int shortIndex = 0;
             while (LonggerStr.charAt(index++) == ShorterStr.charAt(shortIndex++) && shortIndex < ShorterStr.length()); 
             if (shortIndex<ShorterStr.length()-1) {
                mark=-1;
            }
             return mark;
        }  
       
      }
    
      return mark;
    
 }
    
    
    public static void main(String[] args) {
        String str1 ="rewrf3eucksfddw";
        String str2 = "fuck";
        
        int result = getIndex(str1, str2);
        System.out.println(result);
        
    }
    

}

 

posted @ 2018-12-19 12:39  toov5  阅读(459)  评论(0编辑  收藏  举报