22 Delimiting Strings
Many programs, whether they have a textual user interface or a graphical user interface, need to combine an array of String
objects into a single String
object that has a delimiter between every pair of elements. There are several ways of accomplishing this goal.
Motivation
Suppose you want to generate the String
object "Rain,Sleet,Snow"
from a String[]
containing the elements "Rain"
, "Sleet"
, and "Snow"
. One way to think about the desired result is that there is a comma (the delimiter) between every pair of elements. A second way to think about the desired result is that there is a comma after every item except the last one. A third way to think about the desired result is that there is a comma before every item except the first one. As it turns out, each leads to a different implementation.
Review
Since you are going to iterate over the String[]
array and consider each element individually, the first conceptualization is a little awkward to deal with. Specifically, you will need to consider both element i
and i-1
or i+1
at each iteration. If you work with index i-1
you will need to ensure that there are two elements and then initialize the loop control variable to 1
. If you work with index i+1
you will need to ensure that there are two elements and then terminate the loop at the length of the array minus two. Neither is impossible, but both seem unnecessarily complicated if they can be avoided. Fortunately, both of the other conceptualizations only require you to work with one element at a time using an accumulator (as discussed in Chapter 13) so the first conceptualization won’t be considered.
Thinking About The Problem
The other two conceptualizations differ in that one appends the delimiter after concatenating an element to the accumulator, and the other prepends the delimiter before concatenating an element to the accumulator
Appending the Delimiter
The second conceptualization requires you to append the delimiter after every item except the last one. Assuming item
contains the String[]
and delim
contains the delimiter, this can be implemented as follows:
// Append the delimiter when needed result = ""; for (int i = 0; i < item.length; ++i) { result += item[i]; if (i < item.length - 1) { result += delim; } }
It is also possible to treat an array of length 1 as a special case, initializing the accumulator accordingly, and then start with element 1 as in the following implementation:
// 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]; }
This eliminates the need for an if
statement within the loop.
Prepending the Delimiter
The third conceptualization requires you to prepend the delimiter before every item except the first one.