使用递归的java子串

whhtz7ly  于 2021-06-30  发布在  Java
关注(0)|答案(1)|浏览(392)

我正在尝试使用递归实现我自己的子字符串(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));
    }

输出:“错误”

j0pj023g

j0pj023g1#

此解决方案适用于递归

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

相关问题