Categories: Miscellaneous

Getting Substring from an String with Swift

Greetings!

So I wrote this function and then felt like sharing it with you guys.
Which basically helps you retrieve a Substring from an string.

Here is the function.

   
func getSubstring(mainString: String, startString: String,endString: String) -> String
        {
        var tempString = mainString.lowercaseString
        let start = tempString.rangeOfString(startString)
        let range = Range(start: tempString.startIndex, end: (start?.endIndex)!)
        tempString.removeRange(range)
            
        let substring = tempString.substringWithRange(Range(start: tempString.startIndex,end: (tempString.rangeOfString(endString)?.startIndex)!))
        return substring
        }

How it works?

You need to pass your whole string along with the string at -1th index of the starting index of your substring and the string at +1th index of the ending index of your substring. In return you’ll get your substring.

Check the result below:

 

Ciao!

Aaqib Hussain

Aaqib is an enthusiastic programmer with the love of Swift and anything that looks like Swift i.e Kotlin. He loves writing code in Swift, and exploring new technology and platforms. He likes to listen to old music. When he is not writing code, he's probably spend his time watching movies, tv-shows or anime, or either doing some research for writing the next article. He started Kode Snippets in 2015.

Recent Posts

Things to know when moving to Germany

This article covers some important things you must know when you are considering a move…

3 years ago

Unit Testing in Android for Dummies

What is Unit Testing? In its simplest term, unit testing is testing a small piece…

4 years ago

Factory Design Pattern

In this article, you will learn about a type of Creational Design Pattern which is…

5 years ago

Creating Target specific Theme in iOS

In this tutorial, you will go through the use of targets to achieve two separate…

5 years ago

Facade Design Pattern

In this article, you will learn about a type of Structural Design Pattern which is…

5 years ago

Singleton Design Pattern

In this article you will learn about a type of Creational Design Pattern which is…

5 years ago