我是Java的初学者并且接受过家庭作业来创建indexOf方法的副本,该方法接收字符串作为参数。我必须检查收到的字符串是否是原始字符串的子字符串,如果是,我必须返回它的索引。例如:如果原始字符串是"母亲",str =="其他"将返回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;
}
请帮忙! 提前谢谢!
答案 0 :(得分:0)
这是我提出的解决方案:
注意:它不在包含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