I have the following code to generate all possible substrings of a string :
import java.util.*;
public class PlayString
{
public static void main(String[] args)
{
String st = "ABC";
char[] arr = new char[st.length()];
for (int x = 0; x < st.length(); x++)
{
arr[x] = st.charAt(x);
}
StringBuffer sb = new StringBuffer();
combination(arr, 0, st.length() - 1, sb);
}
public static void combination(char[] arr, int index, int b, StringBuffer sb)
{
for (int i = index; i <= b; i++)
{
sb.append(arr[i]);
System.out.println(sb);
combination(arr, i + 1, b, sb);
sb.setLength(sb.length() - 1);
}
}
}
My question is : in the last line when sb.setLength(sb.length()-1) what happens exactly ? like for example if the string input is “abc” then the output will go like a , ab , abc , then what happens when the length is set ? and then after it is set , is there any thing truncated ? and what happens when we try to append an element after that ?
I mean if input string is “abc” then after the string buffer has “abc” in it and its length is now 3 , then we do sb.setLength(sb.length() – 1 ) so now the length should be now , so which element exactly is truncated ? and when we append later what happens?
If we replace the function combination() as follows
You will see the following output
>
Hope it explains the reason.