DEV Community

loading...

String Manipulations in Swift 4

tiptopgs profile image Jen Chang Originally published at Medium on ・2 min read

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:

Sample constant string

What if you want to repeat a string multiple times? You can use the repeating feature:

Say my name, say my name…

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.

A multi-line String literal representation

To parse through each character in a String, you can do the following:

Loop through each of the character in a string

There are several ways to get the string portion or content between the two paragraph tags.

Using indexes to extract parts of a string

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?

Looping through each of the characters in the String by their respective index (or position)

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:

Looping through the multi-line String literal to extract the position of the characters “x” and “o”

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.

Discussion

pic
Editor guide