我正在尝试比较两个字符串,以查看一个字符串是否包含另一个字符串以及哪个点。所以基本上我试图找到 indexOf 。但是,我不想使用它。
这是我编写的代码,使用indexOf完美地运行:
import java.lang.*;
public class Index
{
public static void indexOf(String main, String check)
{
System.out.println(main.toLowerCase().indexOf(check.toLowerCase()));
}
public static void main(String[] args)
{
indexOf("Barack Obama", "Obama");
}
}
然而,问题是我不想使用 indexOf 。此外,我正在尝试将代码 递归 。
所以我尝试编写这段代码:
public class Index
{
public static int indexOf(String main, String check)
{
int n = check.length();
int i = main.length();
int h = 0;
for (int j = 0; j < n; j++)
{
if (main.charAt(j) == check.charAt(j)) h++;
}
return h - 1;
}
public static void main(String[] args)
{
System.out.println(indexOf("Barack", "B"));
}
}
然而,这个人根本没有做到这一点,它甚至不是递归的。
无论如何,我可以使这个方法递归,而不是使用indexOf?
答案 0 :(得分:3)
在使方法递归之前,以递归方式考虑您的任务是有益的。子字符串从字符串的特定索引开始是什么意思?递归解释它的一种方法如下:
子串的索引是
- -1,如果字符串短于子字符串
- 0,如果您的字符串以子字符串开头,或
- 1 + 子字符串的索引,当删除字符串的第一个字符时,返回值为正
- -1如果子串的索引返回-1
突出显示部分表示已应用递归的位置:为了计算子字符串的索引,我们必须在较短的字符串中计算子字符串的索引。
这个描述几乎可以转换为递归方法:
int indexOf(String str, String sub) {
if (str.length() < sub.length()) return -1;
if (str.startsWith(sub)) return 0;
int res = indexOf(str.substring(1), sub);
return res < 0 ? res : 1+res;
}
答案 1 :(得分:2)
package com.company;
public class Index {
public static int indexOf(String main, String check)
{
if (main.startsWith(check)) {
return 0;
} else if (main.length() < check.length()) {
return -1;
} else {
int indexOf = indexOf(main.substring(1), check);
return indexOf < 0 ? -1 : 1 + indexOf;
}
}
public static void main(String[] args)
{
System.out.println(indexOf("Barack Obama", "Obama"));
}
}
答案 2 :(得分:1)
如果您也不想使用startsWith(),这也可以正常工作。如果上一部分全部匹配,则检查字符串的一部分与主字符串匹配。
public class Index {
public static int indexOf(String main, String check) {
int i = main.length();
for (int j = 0; j < i; j++) {
if (main.charAt(j) == check.charAt(0)) {
if (check.length() > 1) {
if (indexOf(main, check.substring(1)) == j + 1) {
return j;
}
} else {
return j;
}
}
}
return -1;
}
public static void main(String[] args) {
System.out.println(indexOf("My name is XYZ", "ashfbs"));//returns -1;
System.out.println(indexOf("My name is XYZ", "is"));//returns 8;
}
}