Lenonor
Lenonor

Reputation: 47

String Buffer SetLength(X) Method Then Appending

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?

Upvotes: 1

Views: 980

Answers (1)

sharadendu sinha
sharadendu sinha

Reputation: 827

If we replace the function combination() as follows

public static void combination(char[] arr, int index, int b, StringBuffer sb)
    {
        for (int i = index; i <= b; i++)
        {
            System.out.println("i :" + i);
            sb.append(arr[i]);
            System.out.println(sb);
            combination(arr, i + 1, b, sb);
            System.out.println("setting length:" + (sb.length() -1) + ": index :" + index);
            sb.setLength(sb.length() - 1);
        }
    }

You will see the following output >

i :0
A
i :1
AB
i :2
ABC
setting length:2: index :2
setting length:1: index :1
i :2
AC
setting length:1: index :1
setting length:0: index :0
i :1
B
i :2
BC
setting length:1: index :2
setting length:0: index :0
i :2
C
setting length:0: index :0

Hope it explains the reason.

Upvotes: 1

Related Questions