|
Delimiting Strings
A Programming Pattern |
|
Prof. David Bernstein |
| Computer Science Department |
| bernstdh@jmu.edu |
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)String
object "Rain,Sleet,Snow" from
a String[] containing the three wordsString
// 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];
}
"Rain, Sleet, and Snow")if
statement /**
* 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);
}
"rain, sleet, and snow" rather than
"rain, sleet and snow"
", " as delim
", and " as lastdelim