First thing first, Swift 4’s API for String has been beefed up with many powerful capabilities. Strings and String manipulations are essentials for any or most solutions. Swift language offers some powerful way to do this. So let’s review some of the language capabilities.
To create a string, you can assign it to a property:
What if you want to repeat a string multiple times? You can use the repeating feature:
Sometimes you need to represent a multi-line string and this can be done easily with 3 opening quotes and 3 closing quotes. Each line in the multi-line string literal contains an end-of-line character \n.
To parse through each character in a String, you can do the following:
There are several ways to get the string portion or content between the two paragraph tags.
Let me explain what’s going on. The first approach above makes assumption that the
tags exist. So we use a fixed offset from the start and end of the string to extract the middle portion. On the other hand, we can use the second approach to determine the index based on identifiable parts of the tags. Because we may not find the matching index, we default to using the start and end index of the original string. Which way do you prefer? Is there a better way of doing the same? Feel free to share it in the comments below.Sometimes we may need to identify the position of the character in the string. How do we do this?
Note that we are advancing the offset by the position number from the String’s start index each time to retrieve the next character. Sometimes, you might only care about the position for “x” and “o” so you can use comparisons to only print those out. See the following example:
Where to go from here?
String manipulations in Swift have come a long way. Check out the Apple documentation for more: Swift Standard Library Reference — String and post some of your favorite String manipulations in the comments below.
Top comments (0)