我的任务是创建执行以下操作的方法getCharAfterNthOccurance(String text,int n,String target):
/**
* If n is not positive, throws an IllegalArgumentException.
*
* Otherwise, returns the character that follows the nth occurrence of the
* target inside the text.
*
* If the target does not occur n times within the text, or if the nth
* occurrence is not followed by a character, throws NoSuchElementException.
*/
不使用任何.substring方法。这是我到目前为止的代码:
public static char getCharAfterNthOccurrence (String text, int n, String target)
{
// Your implementation goes here. You will find the two-parameter .indexOf
// method on strings very helpful. Do not use any of the .substring methods,
// or your program will be too slow.
if (target.length()>=text.length())
{
throw new NoSuchElementException();
}
if (n<=0 || text.length()==0)
{
throw new IllegalArgumentException();
}
if (n>text.length()+target.length())
{
throw new NoSuchElementException();
}
if (nthOccurrence(text,target,n)==-1)
{
throw new NoSuchElementException();
}
if (target.equals(""))
{
return text.charAt(n-1);
}
if (n == 1)
{
return text.charAt(text.indexOf(target)+target.length());
}
return text.charAt(nthOccurrence(text,target,n)-1);
}
public static int nthOccurrence(String str, String c, int n)
{
int pos = str.indexOf(c);
while (n-- > 0 && pos != -1)
{
pos = str.indexOf(c, pos+1);
}
return pos;
}
以下是一些测试用例:
@Test
public void testGetCharAfterNthOccurrence ()
{
assertEquals('a', getCharAfterNthOccurrence("aaaaab", 1, "a"));
assertEquals('a', getCharAfterNthOccurrence("aaaaab", 2, "a"));
assertEquals('a', getCharAfterNthOccurrence("aaaaab", 3, "a"));
assertEquals('a', getCharAfterNthOccurrence("aaaaab", 4, "a"));
//assertEquals('b', getCharAfterNthOccurrence("aaaaab", 5, "a"));
assertEquals('d', getCharAfterNthOccurrence("abcdefabcabczabcc", 1, "abc"));
// assertEquals('a', getCharAfterNthOccurrence("abcdefabcabczabcc", 2, "abc"));
assertEquals('z', getCharAfterNthOccurrence("abcdefabcabczabcc", 3, "abc"));
// assertEquals('d', getCharAfterNthOccurrence("abcDABCd", 1, "ABC"));
}
被注释掉的那些(//)是目前正在失败的那些,我不知道如何继续。第一个失败的测试用例获得NoSuchElementException,第二个失败的测试用例期望得到&lt; 99&gt;但收到&lt; 97&gt;,第三个失败的测试用例得到NoSuchElementException可能是因为它正在寻找大写字母而没有找到它们。有什么建议吗?