To split a string into an array of words in Swift, you can use the components(separatedBy:)
method of the String
class. This method splits the string into an array of substrings based on a given delimiter.
In this case, the delimiter we want to use is the white space character (" "), which separates words in a sentence. Here's an example of how to split a string into an array of words:
main.swift199 chars4 lines
In this example, we first define a string variable sentence
that contains the sentence we want to split into words. We then call the components(separatedBy:)
method on sentence
and pass in the delimiter as an argument.
The result is an array of strings words
, where each element contains a word from the original sentence. We print out words
using the print()
function to verify that the split was successful.
Note that components(separatedBy:)
returns an array of strings, so the resulting array words
is of type [String]
. If you need to perform additional operations on this array, you can use array methods such as .count
and .map()
.
gistlibby LogSnag