Search code examples
javarecursionsubstringcomputer-science

Substring using recursion


I'm trying to implement my own substring (fromIndex, toIndex) function using recursion. I have tried several ways of doing this, but there are still errors. Can someone help me with this? This is my code so far:

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);
    }

example:

public static void main(String[] args) {
        RecursiveString rs=new RecursiveString("abcesf");
        System.out.println(rs.subString(2, 4));
    }

output: "error"


Solution

  • This solution works for recursive

    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);
        }
    }
    }
    
    

    OUTPUT:

    Hello World
    Hel