使用递归的子串
Substring using recursion
我正在尝试使用递归实现我自己的子字符串 (fromIndex, toIndex) 函数。我已经尝试了几种方法来做到这一点,但仍然存在错误。有人可以帮我弄这个吗?到目前为止,这是我的代码:
String s;
RecursiveString(String myS){
s=myS;
}
String subString(int from, int to) {
if(this.s.isEmpty())return "hi";
else if(from==this.s.length()-1)return "";
else if(from==to)return "error";
return this.subString(from+1, to);
}
示例:
public static void main(String[] args) {
RecursiveString rs=new RecursiveString("abcesf");
System.out.println(rs.subString(2, 4));
}
输出:“错误”
此解决方案适用于递归
public class HelloWorld{
public static void main(String []args){
System.out.println("Hello World");
RecursiveString.s = "HelloWorld";
System.out.println(RecursiveString.subString(0,3));
}
public static class RecursiveString {
public static String s;
public static String subString(int from, int to) {
if(s.isEmpty())return "hi";
else if(from==s.length()-1)return "";
else if(from==to)return "";
return s.charAt(from) + subString(from+1, to);
}
}
}
输出:
Hello World
Hel
我正在尝试使用递归实现我自己的子字符串 (fromIndex, toIndex) 函数。我已经尝试了几种方法来做到这一点,但仍然存在错误。有人可以帮我弄这个吗?到目前为止,这是我的代码:
String s;
RecursiveString(String myS){
s=myS;
}
String subString(int from, int to) {
if(this.s.isEmpty())return "hi";
else if(from==this.s.length()-1)return "";
else if(from==to)return "error";
return this.subString(from+1, to);
}
示例:
public static void main(String[] args) {
RecursiveString rs=new RecursiveString("abcesf");
System.out.println(rs.subString(2, 4));
}
输出:“错误”
此解决方案适用于递归
public class HelloWorld{
public static void main(String []args){
System.out.println("Hello World");
RecursiveString.s = "HelloWorld";
System.out.println(RecursiveString.subString(0,3));
}
public static class RecursiveString {
public static String s;
public static String subString(int from, int to) {
if(s.isEmpty())return "hi";
else if(from==s.length()-1)return "";
else if(from==to)return "";
return s.charAt(from) + subString(from+1, to);
}
}
}
输出:
Hello World
Hel