【问题标题】:Creating my own myindexof method创建我自己的 myindexof 方法
【发布时间】:2016-06-20 23:42:52
【问题描述】:

我是 Java 初学者,收到了创建 indexOf 方法副本的作业,该方法接收字符串作为参数。我必须检查收到的字符串是否是原始字符串的子字符串,如果是,我必须返回它的索引。例如:如果原始字符串是“mother”,str ==“other”将返回 1。如果 str 不是子字符串,则返回 -1。我必须只使用 String 类的 length() 和/或 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;
}

请帮忙! 提前致谢!

【问题讨论】:

  • 好吧,首先摆脱w3w4array。接下来,想想那个内部循环应该做什么。它应该比较str所有 个字符与objectStr开始于 index 的字符,即objectStr.charAt(index + indexSubstring) == str.charAt(indexSubstring)。内部循环的结果应该是一个布尔值,表明 所有 个字符是否匹配。如果是,则返回 index 的值。如果外部循环退出,则未找到匹配项,因此返回 -1。看看这是否能让你走上正确的道路。

标签: java arrays string indexof


【解决方案1】:

这是我想出的一个解决方案:

注意:它不像你的那样在包含 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-01
    • 1970-01-01
    相关资源
    最近更新 更多