用java查找字符串里的字符_java – 使用递归查找字符串中的字符

你的尝试很好,但并不完全.以下是基于您的正确实现:

public static int indexOf(char ch, String str) {

// Returns the index of the of the character ch

if (str == null || str.equals("")) {

// base case: no more string to search; return -1

return -1;

} else if (ch == str.charAt(0)) {

// base case: ch is at the beginning of str; return 0

return 0;

}

// recursive step

int subIndex = indexOf(ch, str.substring(1));

return subIndex == -1 ? -1 : 1 + subIndex;

}

您的尝试有两个问题:

在else if部分,你找到了这个角色,所以正确的做法是停止递归,但是你继续它.

在最后一个return语句中,您需要在递归调用中添加1(如果最终找到该字符),作为累积总索引号的方法.


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部