Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Dynamic Text Builder

Problem Statement

Write a Java program that implements a method to build a formatted string in CSV (comma-separated values) format using StringBuilder, appending elements from an input array. The program should create a string where array elements are separated by commas and test the implementation with arrays of varying sizes, including edge cases like empty arrays and single-element arrays. You can visualize this as assembling a row of data for a spreadsheet, where each item from a list is neatly joined with commas, ensuring the output is compact and properly formatted.

Input: An array of strings (e.g., ["apple", "banana", "cherry"]). Output: A single string in CSV format (e.g., "apple,banana,cherry"). Constraints:

  • Array length is between 0 and 10^5.
  • Each string element contains printable ASCII characters and may be empty or null.
  • The input array may be null or empty. Example:
  • Input: ["apple", "banana", "cherry"]
  • Output: "apple,banana,cherry"
  • Explanation: Elements are joined with commas.
  • Input: []
  • Output: ""
  • Explanation: Empty array returns an empty string.
  • Input: ["solo"]
  • Output: "solo"
  • Explanation: Single element has no commas.

Pseudocode

FUNCTION buildCSVRow(array)
    IF array is null THEN
        RETURN null
    ENDIF
    IF array is empty THEN
        RETURN empty string
    ENDIF
    CREATE stringBuilder for result
    FOR each element in array
        IF element is not null THEN
            APPEND element to stringBuilder
            IF not last element THEN
                APPEND comma to stringBuilder
            ENDIF
        ENDIF
    ENDFOR
    RETURN stringBuilder as string
ENDFUNCTION

FUNCTION main()
    SET testArrays to array of string arrays with varying sizes
    FOR each array in testArrays
        PRINT input array
        CALL buildCSVRow(array)
        PRINT resulting CSV string
    ENDFOR
ENDFUNCTION

Algorithm Steps

  1. Check if the input array is null; if so, return null.
  2. Check if the input array is empty; if so, return an empty string.
  3. Initialize a StringBuilder for the result.
  4. Iterate through the array: a. If the current element is not null, append it to the StringBuilder. b. If it is not the last element, append a comma.
  5. Return the StringBuilder’s content as a string.
  6. In the main method, test with arrays of different sizes (e.g., empty, single-element, multiple elements, and large arrays) and print the input and output.

Java Implementation

public class DynamicTextBuilder {
    // Builds a CSV row from an array using StringBuilder
    public String buildCSVRow(String[] array) {
        if (array == null) {
            return null;
        }
        if (array.length == 0) {
            return "";
        }
        StringBuilder result = new StringBuilder();
        for (int i = 0; i < array.length; i++) {
            if (array[i] != null) {
                result.append(array[i]);
                if (i < array.length - 1) {
                    result.append(",");
                }
            }
        }
        return result.toString();
    }

    // Main method to test buildCSVRow with various array sizes
    public static void main(String[] args) {
        DynamicTextBuilder builder = new DynamicTextBuilder();

        // Test cases
        String[][] testArrays = {
            {"apple", "banana", "cherry"}, // Multiple elements
            {},                           // Empty array
            {"solo"},                     // Single element
            generateLargeArray(1000),     // Large array
            {null, "test", null},         // Array with null elements
            null                          // Null array
        };

        for (int i = 0; i < testArrays.length; i++) {
            System.out.println("Test case " + (i + 1) + ":");
            System.out.print("Input array: [");
            if (testArrays[i] != null) {
                for (int j = 0; j < testArrays[i].length; j++) {
                    System.out.print(testArrays[i][j] != null ? "\"" + testArrays[i][j] + "\"" : "null");
                    if (j < testArrays[i].length - 1) {
                        System.out.print(", ");
                    }
                }
            } else {
                System.out.print("null");
            }
            System.out.println("]");
            String result = builder.buildCSVRow(testArrays[i]);
            System.out.println("CSV output: \"" + (result != null && result.length() > 50 ? result.substring(0, 50) + "..." : result) + "\"\n");
        }
    }

    // Helper method to generate a large array
    private static String[] generateLargeArray(int size) {
        String[] largeArray = new String[size];
        for (int i = 0; i < size; i++) {
            largeArray[i] = "item" + i;
        }
        return largeArray;
    }
}

Output

Running the main method produces:

Test case 1:
Input array: ["apple", "banana", "cherry"]
CSV output: "apple,banana,cherry"

Test case 2:
Input array: []
CSV output: ""

Test case 3:
Input array: ["solo"]
CSV output: "solo"

Test case 4:
Input array: ["item0", "item1", "item2", ..., "item999"]
CSV output: "item0,item1,item2,...,item998,item999"

Test case 5:
Input array: [null, "test", null]
CSV output: "test"

Test case 6:
Input array: [null]
CSV output: "null"

Explanation:

  • Test case 1: ["apple", "banana", "cherry"]"apple,banana,cherry".
  • Test case 2: Empty array []"".
  • Test case 3: ["solo"]"solo".
  • Test case 4: Large array (1000 elements) → "item0,item1,...,item999".
  • Test case 5: [null, "test", null]"test" (skips null elements).
  • Test case 6: null"null".

How It Works

  • Step 1: Check for null or empty array; return null or empty string as needed.
  • Step 2: Initialize StringBuilder for efficient string construction.
  • Step 3: Iterate through the array:
    • Append non-null elements.
    • Add a comma after each element except the last.
  • Step 4: Return the StringBuilder’s content as a string.
  • Example Trace (Test case 1):
    • Input: ["apple", "banana", "cherry"].
    • Initialize: result = "".
    • i=0: Append "apple,"result = "apple,".
    • i=1: Append "banana,"result = "apple,banana,".
    • i=2: Append "cherry"result = "apple,banana,cherry".
  • Main Method: Tests with arrays of varying sizes, including empty, single-element, large, and arrays with null elements.
  • CSV Property: Ensures proper formatting with commas between elements and no trailing comma.

Complexity Analysis Table

OperationTime ComplexitySpace Complexity
Building CSVO(n * m)O(n * m)
Full AlgorithmO(n * m)O(n * m)

Note:

  • n is the number of elements in the array, m is the average length of each string element.
  • Time complexity: O(n * m) for appending each character of each string to StringBuilder.
  • Space complexity: O(n * m) for the StringBuilder to store the final CSV string.
  • Worst case: O(n * m) time and space when all elements are non-null and long.

✅ Tip: Use StringBuilder for efficient string concatenation when building formatted strings like CSV rows. Test with null elements and large arrays to ensure robustness.

⚠ Warning: Check for null array elements to avoid appending "null" as a string literal. Ensure no trailing comma is added to maintain proper CSV format.