OneBite.Dev - Coding blog in a bite size

Split A String By Empty Space In Swift

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

In this article, we will explore how to split a string by empty space using Swift. This is a fundamental skill that can come in handy in various coding scenarios.

Code snippet for Splitting a String by Empty Space

Here’s a simple code snippet that accomplishes this task:

let myString = "Hello World"
let splitString = myString.split(separator: " ")

In the above code snippet, we initiated a new string myString and assigned it the value “Hello World”. We then split the string using the split function and saved the result in the splitString.

Code Explanation for Splitting a String by Empty Space

Let’s explain each step in detail:

  1. let myString = "Hello World": Here, we initiate a new string variable myString and assign it the value of “Hello World”.

  2. let splitString = myString.split(separator: " "): This is where the split function comes into play.

    The split method in Swift is used to divide a String into an array of smaller strings, split according to defined separators. In this case, the separator is an empty space (” ”). This means the string will be split every time an empty space is encountered.

    The result will be saved in a new variable splitString.

Given that "Hello World" has an empty space in between “Hello” and “World”, the splitString will hence contain two elements: “Hello” and “World”.

To sum up, splitting a string by empty spaces in Swift is straightforward and only requires the usage of the split method, with ” ” as the separator. This resulting array of smaller strings can then be manipulated as per the needs of your program.

swift