2016-06-20 151 views
1

我是一名Java初學者,收到作業來創建一個indexOf方法的副本,它接收一個字符串作爲參數。我必須檢查收到的字符串是否是原始字符串的子字符串,如果是,我必須返回它的索引。例如:如果原始字符串是「mother」,str ==「other」將返回1.如果str不是子字符串,則返回-1。我只需要使用String類的length()和/或charAt()方法來創建它。創建我自己的myindexof方法

我被困在它很長一段時間。我已經試過許多種類代碼,但沒有成功......

例如:

public int myIndexOf1(String str) 
{ 
    String objectStr = this._st; 
    Word w3 = new Word(objectStr); 
    Word w4 = new Word(str); 
    char[] array = w3.toCharacterArray(); 

    int firstShowIndex = 0; 
    int length = array.length; 
    int max = objectStr.length() - str.length(); 
    for (int index = 0; index < max; index++) 
    { 
     for (int indexSubstring = 0; indexSubstring < str.length(); indexSubstring++) 
     { 
      if (objectStr.charAt(index) == str.charAt(indexSubstring)) 
      { 
       firstShowIndex = index; 
       break; 
      } 
      else 
       firstShowIndex = -1; 
     } 
    } 

    return firstShowIndex; 
} 

請幫幫忙! 在此先感謝!

+1

好,通過擺脫w3','w4'和'array'的'開始。接下來,思考內部循環應該做什麼。它應該比較'str'的​​ all *個字符和'objectStr' *的*字符,即'objectStr.charAt(index + indexSubstring)== str.charAt(indexSubstring)'。內部循環的結果應該是一個布爾值,表示是否所有*字符匹配。如果他們這樣做,則返回'index'的值。如果外循環退出,找不到匹配,所以返回'-1'。看看是否讓你走在正確的道路上。 – Andreas

回答

0

下面是我想出了一個解決方案:

注意:這是不是包含字符串作爲一個私有成員爲您做一類的範圍內,但你能適應它。

public static int myIndexOf (String mainStr, String otherStr) 
{ 
    // either is null 
    if (mainStr == null || otherStr == null) 
    { 
     return -1; 
    } 

    int len = mainStr.length(); 
    int lenOfOther = otherStr.length(); 

    // special case: both strings are empty 
    if (len == 0 && lenOfOther == 0) 
    { 
     return 0; 
    } 

    // for each char in the main string 
    for (int i = 0; i < len && len - i >= lenOfOther; i++) 
    { 
     // see if we can match char for char in the otherStr 
     int k = 0; 
     while (k < lenOfOther && mainStr.charAt(k + i) == otherStr.charAt(k)) 
     { 
      k++; 
     } 
     if (k == lenOfOther) 
     { 
      return i; 
     } 
    } 

    // nothing found 
    return -1; 
} 

使用

public static void main(String[] args) 
{ 
    String mainStr = "mother"; 
    String otherStr = "other"; 

    int index = myIndexOf(mainStr, otherStr); 
    System.out.println("My Index: " + index); 

    // Just for a sanity check 
    System.out.println("String Index: " + mainStr.indexOf(otherStr)); 
} 

輸出

My Index: 1 
String Index: 1