-1

im trying to do find the all the substrings in a string,i have written the following codes, but i have some unwanted outputs as you see below: the method first print the substring (0,1) then it calls itself by incrementing b with 1 and keep going like this, when b>string's length, it will preincrement a,and passes a+1 to the b, and it continues like this, until the last substring where a+1==string's length, this when my recurive program should terminate.

public static void main(String[] args) {
    recsub("java",0,1);
}

public static void recsub(String str,int a,int b){
    if(b>str.length()) {
        System.out.println();
        recsub(str,++a,a+1);
    }
    else {
        System.out.print(str.substring(a,b)+" "); 
    }
    if((a+1)==str.length()) {

    } 
    else {
        recsub(str,a,b+1);
    }

The output from this code is:

j ja jav java 
a av ava 
v va
a
a
v va
a
a 

or Can I break out through this method and return to the main, whenever the program enters that if (if(a+1)==...), like breaking a loop?

1 Answers1

0

If you structure your logic well, you shouldn't have to break a routine like that, although it's quite legal (and often useful) to return as needed.

The error is in your second recursion: this should be conditional on the substring size b being short enough.

I've taken the liberty of replacing one-letter variable names (a -> start_pos, b -> size), changing the test string ("java" has two a's, so it's harder to track), and cleaning up the white space.

public class substr {
  public static void main(String[] args) {
    recsub("abcd", 0, 1);
  }

  public static void recsub(String str, int start_pos, int size){
    if (size > str.length()) {
      // Print newline; restart with next character
      System.out.println();
      recsub(str, ++start_pos, start_pos+1);
    }
    else {
      // Print one substring
      System.out.print(str.substring(start_pos, size)+" ");
      if (start_pos+1 < str.length()) {
        recsub(str, start_pos, size+1);
      }
    }
  }
}

Output:

a ab abc abcd 
b bc bcd 
c cd 
d 
Prune
  • 76,765
  • 14
  • 60
  • 81