创建我自己的 myindexof 方法

Creating my own myindexof method

我是 Java 的初学者,并收到作业来创建 indexOf 方法的副本,该方法接收字符串作为参数。我必须检查收到的字符串是否是原始字符串的子字符串,如果是,我必须 return 它的索引。例如:如果原始字符串是 "mother",str == "other" 将 return 1。如果 str 不是子字符串,则 return -1。我必须仅使用 String class.

的方法 length() and/or charAt() 创建它

我卡了好久。我已经尝试了多种代码,但都没有成功...

例如:

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;
}

请帮忙! 提前致谢!

这是我想出的解决方案:

注意:它不在 class 的上下文中,它像您一样包含一个 String 作为私有成员,但您可以对其进行调整。

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