OneBite.Dev - Coding blog in a bite size

Split A String By A Delimiter In Swift

Code snippet for how to Split A String By A Delimiter In Swift with sample and detail explanation

Manipulating strings is a fundamental skill in any programming language, and of course, Swift is no exception. In this article, we will focus on how to split a string by a delimiter, an essential task in many coding scenarios, whether for everyday programming or complex software development.

Code Snippet: Split A String By A Delimiter In Swift

In Swift, splitting a string by a delimiter is a straightforward task. Below you can find a code snippet illustrating this process:

let originalString = "Hello, lets, split, this, string"
let delimiter = ", "
let splitString = originalString.components(separatedBy: delimiter)
print(splitString)

When we run this code, the output will be:

["Hello", "lets", "split", "this", "string"]

Code Explanation: Split A String By A Delimiter In Swift

Now, let’s move on to a step-by-step explanation of this code.

  1. let originalString = "Hello, lets, split, this, string": In this line, we initialize a variable named originalString with the string that we want to split.

  2. let delimiter = ", ": The delimiter variable is initialized with the string on which we want to split the originalString. In our case, it’s a comma followed by a space.

  3. let splitString = originalString.components(separatedBy: delimiter): Here, we use the components(separatedBy:) method on our originalString. This method is a part of the String class in Swift, and what it does is return an array of substrings, each of which is a section of the original string divided by the separator - our delimiter in this case.

  4. print(splitString): Finally, we print out our result, which is an array of substrings. Each element in the array is a word from the originalString, split at every instance of the delimiter , .

By understanding and using the components(separatedBy:) method, one can quite conveniently split a string by any delimiter in Swift. Whether it’s for data parsing, text manipulation, or any other scenario where you need to break down a string, this method comes in very handy.

swift