Check for String prefix in Swift
This tutorial is based on the topic prefix which falls under the strings Prefix means working on the starting on the starting part of a string. In this post, we will discuss a few ways/methods in strings that will be helpful to extract/fetch the starting part or call it the prefix of a string.
Let’s start with the first method:
Method 1- To check if a substring is present at the start or not
To work on this, there is a method in Swift called hasprefix()
which takes the substring, checks it, and returns a bool value as-
let str1="CodeSpeedy" let str2=str1.hasPrefix("Code") print(str2)
Output-
true
Method 2-To get the substring using length
For this method, there is a function known as prefix() which accepts the parameter in integer and returns the substring up to the integer given as-
let str1="CodeSpeedy" let str2=str1.prefix(4) print(str2)
Output-
Code
Method 3: To get the substring using the index
This method is to fetch the substring from the start/prefix using an index. There is a method in Swift known as string.index()
which points to a particular index. And then we have two ways in prefixes known as through and upto, both have their different purposes if you want to include the particular element at the given position use through, but if you don’t want to include the given position, go for upto. You will get a better understanding of its implementation-
Using through-
let str1="CodeSpeedy" let index=str1.index(str1.startIndex,offsetBy :4) let str2=str1.prefix(through: index) print(str2)
Output-
CodeS
Here, through was used and its output included the element where the cursor was pointing.
Using upto-
let str1="CodeSpeedy" let index=str1.index(str1.startIndex,offsetBy :4) let str2=str1.prefix(upTo: index) print(str2)
Output-
Code
Method 4: To get the prefix using a character and its occurrence
Quite often, we are not sure about the length and position but we know the character and its occurrence, for example, you may need the element upto the first or last frequency of an element, maybe a particular letter, e. Here we have a method in Swift known as lastindex
and firstindex
which iterates over the string to check for the element and its occurrence. Here’s the implementation for better understanding-
let str1="CodeSpeedy" if let index=str1.firstIndex(of:"e") { print(str1.prefix(through: index)) }
Output-
Code
let str1="CodeSpeedy" if let index=str1.lastIndex(of:"e") { print(str1.prefix(through: index)) }
Output-
CodeSpee
In this post, we have discussed a few methods related to strings and their prefix using the length, index, and occurrence of a character. I hope you find this tutorial helpful for the project/task. Thanks for reading!
Leave a Reply