Check for String suffix in Swift

This tutorial is based on the topic strings to check for its suffix. It means to work on the end part of a string. Here we have described 4 different methods with different outputs to demonstrate the topic in Swift. Let’s start with the 1st method

Method 1: To Check if a substring is present at the end or not

To do this, we have a function in Swift hasSuffix() which takes the substring as a parameter and returns a bool value.

let str1="CodeSpeedy"
let str2=str1.hasSuffix("Speedy")



Method 2- To get the substrings from the end

Whenever our task is to fetch the string from the end we need to use suffix() which returns the strings of specified length counting from the end.

let str1="CodeSpeedy"
let str2=str1.suffix(6)



Method 3: To get the substring using index in Swift

There is a method String.Index() which takes two parameters as mentioned and then we have used suffix() which has parameter ‘from’ to return the string from the specified index.

let str = "CodeSpeedy"
let index = str.index(str.startIndex, offsetBy:4)

print(str.suffix(from: index))



Method 4: To retrieve a substring from the end using a character and its occurrence-

All the above methods are useful when you know about the index and substring, what if you need to fetch the string by only using the occurrence of an alphabet in a string? For this, we need to use firstIndex(of:) method which takes the parameter as an alphabet and returns the index, and same using the str.suffix(from: index) method we can print the complete string. Also, there is lastIndex(of:) which is the same as firstIndex(of:) just the difference is it will point to the last index. Here is the implementation-

let str = "CodeSpeedy"
if let index = str.firstIndex(of: "e")

{print(str.suffix(from: index))}



As we can observe, index has the index for the first occurrence of e and then we used suffix with the parameter ‘from’ to print the whole string from the index.

So, basically, we have discussed 4 different methods in Swift to print suffix of a string in Swift. Thanks for taking out time and reading this article. I hope you find it helpful for your task/project.

Leave a Reply

Your email address will not be published. Required fields are marked *