To split a string into two substrings in Swift, you can use the split
method or the substrings
property. Here's an example of how to split a string into two substrings at a particular index using both methods:
main.swift213 chars5 lines
In the above example, we first define a String
variable called str
with the value "Hello world!". We then obtain the index of the space character using the index
method and pass in the string's startIndex
and an offset of 5. This gives us the index of the 6th character in the string, which is the space character.
We then use this index to create two substrings: firstString
is created using the string's startIndex
up to, but not including, the space character index. This gives us the "Hello" substring. secondString
is created using the space character index through the end of the string. This gives us the " world!" substring.
Alternatively, we can use the split
method and the substrings
property to achieve the same result:
main.swift186 chars5 lines
Here, we first use the split
method to split the string at the space character. This returns an array of substrings, with a maximum of 2 substrings (maxSplits: 1
) to be returned. We then create two String
variables, firstString
and secondString
, using the first and second substrings in the components
array, respectively.
Note that in the second example, we do not include the space character in any of the substrings, whereas in the first example, we include it in the second substring.
gistlibby LogSnag