JMU
Delimiting Strings
A Programming Pattern


Prof. David Bernstein
James Madison University

Computer Science Department
bernstdh@jmu.edu


Motivation
Motivation (cont.)
Review
Thinking About the Problem
Appending After Every Item But The Last
javaexamples/programmingpatterns/DelimitingStrings.java (Fragment: 10)
        // Append the delimiter when needed
        result = "";        
        for (int i = 0; i < item.length; ++i) {
            result += item[i];
            if (i < item.length - 1) {
                result += delim;
            }
        }
        
Thinking About the Problem (cont.)
Appending After Every Item But The Last; A Length of 1 is a Special Case
javaexamples/programmingpatterns/DelimitingStrings.java (Fragment: 11)
        // Append the delimiter when needed, initializing
        // the accumulator based on the length
        if (item.length > 1) {
            result = item[0] + delim;
        } else if (item.length > 0) {
            result = item[0];
        } else {
            result = "";
        }
        
        for (int i = 1; i < item.length - 1; ++i) {
            result += item[i];
            result += delim;
        }

        if (item.length > 1) {
            result += item[item.length - 1];
        }
        
Thinking About the Problem (cont.)
Prepend Before Every Item But The First; A Length of 1 is a Special Case
javaexamples/programmingpatterns/DelimitingStrings.java (Fragment: 12)
        // Prepend the delimiter when needed
        result = "";        
        for (int i = 0; i < item.length; ++i) {
            if (i > 0) {
                result += delim;
            }
            result += item[i];
        }
        
Thinking About the Problem
The Pattern
The Pattern (cont.)
javaexamples/programmingpatterns/DelimitingStrings.java (Fragment: pattern)
    /**
     * Create a delimited String from a String[].
     *
     * @param item   The items to include
     * @param delim  The delimiter to place between all but the last two items
     * @param lastdelim  The delimiter to place between the last two items
     * @return The delimited String
     */
    public static String toDelimitedString(String[] item, 
                                           String delim, String lastdelim) {
        String result;

        result = "";        
        for (int i = 0; i < item.length; ++i) {
            result += item[i];
            if (i  < item.length - 2) {
                result += delim;
            }  else if (i == item.length - 2) {
                result += lastdelim;
            }
        }
        return result;
    }

    /**
     * Create a delimited String from a String[].
     *
     * @param item   The items to include
     * @param delim  The delimiter to place between the items
     * @return The delimited String
     */
    public static String toDelimitedString(String[] item, String delim) {
        return toDelimitedString(item, delim, delim);
    }
        
An Example