Home
Map
String Join, joined ExamplesUse the joined method to join a string array into a string. Use a delimiter comma.
Swift
This page was last reviewed on Aug 23, 2023.
Join. A string array contains many related strings. To combine these into a single string, we can use the joined() func. This is a simple and powerful func.
To join elements together, we use an instance method on the array. The argument is the delimiter string. An empty delimiter can be used.
First example. Here we join a 3-element string array on a comma char. The resulting string contains a comma in between the elements. No delimiter is at the start or the end.
Tip Joined() can handle more than one character in the delimiter. But each delimiter is the same.
// A string array of three elements. let animals = ["cat", "dog", "bird"] // Join the elements together with a comma delimiter. let result = animals.joined(separator: ",") print(result)
cat,dog,bird
Empty delimiter. Sometimes we want to just combine (concatenate) all the strings together. No delimiter is required. We specify an empty string literal as the delimiter.
Tip This is much simpler than a loop and string concats. And on large collections it may have a performance advantage.
// A string array. let values = ["A", "B", "C", "D"] // Join the elements with an empty delimiter. let result = values.joined() print(result) // Display length of the result. print(result.endIndex)
ABCD Index(_rawBits: 262151)
A note. This is an important aspect of joined: it adds no trailing delimiter. So we do not need special logic to remove a final characters.
Review. Joined is the opposite of split. These two methods can round-trip data. With components(), we split apart strings (this is the opposite of joined).
String Split
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Aug 23, 2023 (edit).
Home
Changes
© 2007-2024 Sam Allen.