- Forward


Delimiting Strings
A Programming Pattern


Prof. David Bernstein
James Madison University

Computer Science Department
bernstdh@jmu.edu

Print

Motivation
Back SMYC Forward
  • Frequently:
    • We need to create a String that contains (and/or print) multiple items in a "collection" with a delimiter between items (but not before the first or after the last)
  • General Examples:
    • Comma-Separated-Value (CSV) Format
    • Space (or Tab) Delimited Lines
  • A Specific Example:
    • Creating the String object "Rain,Sleet,Snow" from a String[] containing the three words
  • An Important Point:
    • We can't work with all of the elements at once so we can't use a format String
Motivation (cont.)
Back SMYC Forward
  • The Issue:
    • Not all solutions that are correct are elegant
  • Different Perspectives/Descriptions:
    • There is a delimiter between every pair of items
    • There is a delimiter after every item except the last item and the first item when there is only one
    • There is a delimiter before every item except the first item (which is also the last item when there is only one)
Review
Back SMYC Forward
  • One Way for the Code to Vary:
    • Put a delimiter after an item when there is another to item come
    • Put a delimiter before an item when there was already an item
  • Another Way for the Code to Vary:
    • Handle item 0 as a special case or not
Thinking About the Problem
Back SMYC Forward
Appending After Every Item But The Last
javaexamples/programmingpatterns/DelimitingStrings.java (Fragment: 10)
 
Thinking About the Problem (cont.)
Back SMYC Forward
Appending After Every Item But The Last; A Length of 1 is a Special Case
javaexamples/programmingpatterns/DelimitingStrings.java (Fragment: 11)
 
Thinking About the Problem (cont.)
Back SMYC Forward
Prepend Before Every Item But The First; A Length of 1 is a Special Case
javaexamples/programmingpatterns/DelimitingStrings.java (Fragment: 12)
 
Thinking About the Problem
Back SMYC Forward
  • Comparison:
    • You might not have a preference between appending and prepending
  • A Slightly Different Requirement:
    • You need to be able to use a different delimiter before the last element (e.g., "Rain, Sleet, and Snow")
  • The Resulting Preference:
    • The append approach doesn't require a nested if statement
The Pattern
Back SMYC Forward
  • Approach:
    • Append
  • Method Signatures:
    • Include one with one delimiter and one with two delimiters
The Pattern (cont.)
Back SMYC Forward
javaexamples/programmingpatterns/DelimitingStrings.java (Fragment: pattern)
 
An Example
Back SMYC Forward
  • The Oxford Comma:
    • "rain, sleet, and snow" rather than "rain, sleet and snow"
  • Using the Pattern:
    • Pass ", " as delim
    • Pass ", and " as lastdelim
There's Always More to Learn
Back -