indexOf(String-str)-等于字符串到其他字符串



我需要编写一个方法,在其他字符串上检查"String-str",并返回str启动的索引。

这听起来像是家庭作业,这是一些家庭作业,但对我来说,这是为了考试而学习。。。

我试过了:

public int IndexOf (String str) {
   for (i= 0;i<_st.length();i++)
   {
        if (_st.charAt(i) == str.charAt(i)) {
            i++;
            if (_st.charAt(i) == str.charAt(i)) {
                return i;
            }
        }
   }
   return -1;
 }

但是我没有得到正确的回报。为什么?我走对了路,还是根本不靠近?

恐怕你还差一点。

以下是你必须做的:

  • 在字符串的字符上循环(上的,您应该执行indexOf,我将其称为master)(您正在向右循环)
  • 对于每个字符,请检查其他字符串的字符和该字符是否相同
  • 如果是(可能是同一序列的开始),请检查master中的下一个字符是否与要检查的String匹配(您可能希望循环遍历字符串的元素并逐个检查)
  • 如果不匹配,请继续使用主字符串中的字符

类似于:

Loop master string
for every character (using index i, lets say)
   check whether this is same as first character of the other string
   if it is
      //potential match
      loop through the characters in the child string (lets say using index j)
      match them with the consecutive characters in the master string 
      (something like master[j+i] == sub[j])
       If everything match, 'i' is what you want
       otherwise, continue with the master, hoping you find a match

其他几点:

  • 在java中,方法名称以约定的小写字母(意思是编译器不会抱怨吧,但是你的程序员同事可能)。所以IndexOf实际上应该是indexOf
  • 具有实例变量(类级变量)以_(如_st)不是一个真正好的实践如果你的教授坚持,你可能没有太多选择,但是记住这一点)

恐怕不是很接近。该代码的基本功能是检查两个字符串在任何时候是否有两个字符位于相同的位置,如果是,则返回其中第二个字符的索引。例如,如果_str是"abcdefg",str是"12cd45",您将返回3,因为它们在同一位置有"cd",这是"d"的索引。至少,这是我能说出它实际在做什么的最接近的。这是因为使用相同的索引变量对两个字符串进行索引。

要重新写入indexOf,在_st中查找str,必须扫描_st以查找str中的第一个字符,然后检查其余字符是否匹配;如果没有,从你开始检查的地方向前撞一个地方,然后继续扫描。(你可以做一些优化,但这就是优化的本质。)例如,如果你发现_ststr中索引4处的str的第一个字符有六个字符长,找到第一个字符后,您需要查看其余五个字符(str的索引1-5,包括1-5)是否与_st的索引5-10(包括5-10)匹配(最简单的方法是将str的所有六个字符与_st的从4开始到六个字符的子串进行检查)。如果所有内容都匹配,则返回找到第一个字符的索引(在该示例中为4)。你可以在_st.length() - str.length()停止扫描,因为如果你在那之前还没有找到它,你根本找不到它。

旁敲侧击:不要在每个循环中都调用length函数。JIT可能能够优化调用,但如果您知道_st在该函数执行过程中不会更改(如果您不知道,则应该需要它),请将length()获取到本地,然后引用它。当然,既然你知道你可以在length()之前停下来,你就可以用一个local来记住你可以停在哪里。

如果两个字符串相等,则使用i,但除非找到另一个字符串,否则不能使用第一个始终以0开头的字符串。然后检查下一个字符是否相等,依此类推

希望这能帮助

您的代码在搜索的字符串中循环,如果位置i处的字符匹配,则检查下一个位置。如果字符串在下一个位置匹配,则假定字符串str包含在_st中。

你可能想做的是:

  • 跟踪整个str是否包含在_st中。您可能会检查您正在搜索的字符串的长度是否等于到目前为止匹配的字符数
  • 如果您执行上述操作,那么您可以通过从i的当前值减去到目前为止的匹配次数来获得起始索引。

一个问题:

为什么不使用内置的String.IndexOf()函数?这项任务是为了让你自己实现这个功能吗?

也许Oracle Java API源代码确实有帮助:

   /**
     * Returns the index within this string of the first occurrence of the
     * specified substring. The integer returned is the smallest value
     * <i>k</i> such that:
     * <blockquote><pre>
     * this.startsWith(str, <i>k</i>)
     * </pre></blockquote>
     * is <code>true</code>.
     *
     * @param   str   any string.
     * @return  if the string argument occurs as a substring within this
     *          object, then the index of the first character of the first
     *          such substring is returned; if it does not occur as a
     *          substring, <code>-1</code> is returned.
     */
    public int indexOf(String str) {
    return indexOf(str, 0);
    }
    /**
     * Returns the index within this string of the first occurrence of the
     * specified substring, starting at the specified index.  The integer
     * returned is the smallest value <tt>k</tt> for which:
     * <blockquote><pre>
     *     k &gt;= Math.min(fromIndex, this.length()) && this.startsWith(str, k)
     * </pre></blockquote>
     * If no such value of <i>k</i> exists, then -1 is returned.
     *
     * @param   str         the substring for which to search.
     * @param   fromIndex   the index from which to start the search.
     * @return  the index within this string of the first occurrence of the
     *          specified substring, starting at the specified index.
     */
    public int indexOf(String str, int fromIndex) {
        return indexOf(value, offset, count,
                       str.value, str.offset, str.count, fromIndex);
    }
    /**
     * Code shared by String and StringBuffer to do searches. The
     * source is the character array being searched, and the target
     * is the string being searched for.
     *
     * @param   source       the characters being searched.
     * @param   sourceOffset offset of the source string.
     * @param   sourceCount  count of the source string.
     * @param   target       the characters being searched for.
     * @param   targetOffset offset of the target string.
     * @param   targetCount  count of the target string.
     * @param   fromIndex    the index to begin searching from.
     */
    static int indexOf(char[] source, int sourceOffset, int sourceCount,
                       char[] target, int targetOffset, int targetCount,
                       int fromIndex) {
    if (fromIndex >= sourceCount) {
            return (targetCount == 0 ? sourceCount : -1);
    }
        if (fromIndex < 0) {
            fromIndex = 0;
        }
    if (targetCount == 0) {
        return fromIndex;
    }
        char first  = target[targetOffset];
        int max = sourceOffset + (sourceCount - targetCount);
        for (int i = sourceOffset + fromIndex; i <= max; i++) {
            /* Look for first character. */
            if (source[i] != first) {
                while (++i <= max && source[i] != first);
            }
            /* Found first character, now look at the rest of v2 */
            if (i <= max) {
                int j = i + 1;
                int end = j + targetCount - 1;
                for (int k = targetOffset + 1; j < end && source[j] ==
                         target[k]; j++, k++);
                if (j == end) {
                    /* Found whole string. */
                    return i - sourceOffset;
                }
            }
        }
        return -1;
    }

相关内容

最新更新