1

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"

2
  • 1
    Q: Could you provide a complete example, that compiles? Commented Dec 8, 2020 at 6:52
  • @paulsm4 I just added an example in my code. It is currently not working properly. Commented Dec 8, 2020 at 6:59

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

1 Comment

Java isn't my language I am a C# Guy..so just change it according to your needs.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.