Swift : Get substring with rangeOfString() function example
Problem :
You have a string and you want to get(extract) the sub string from start to {0} and from {1} to end. Ignoring the "just gave" sub string. How to do that?
let str = "Hmmm!, {0} just gave {1} a nice gift."
Solution :
Use substringToIndex()
function to the get sub string from the start to {0}. Use substringFromIndex()
function to get sub string from {1} to end.
To the sub string position, use the rangeOfString()
function calculate the position.
For example :
let str = "Hmmm!, {0} just gave {1} a nice gift."
let myTextBefore1 = str.substringToIndex(text.rangeOfString("{0}")!.startIndex) // "Hmmm!, "
let myTextAfter2 = str.substringFromIndex(text.rangeOfString("{1}")!.endIndex) // " a nice gift"
Hope you find this tutorial useful.
See also : Swift : substringWithRange() function example
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+23.3k Golang : Print out struct values in string format
+51.7k Golang : Disable security check for HTTPS(SSL) with bad or expired certificate
+7.9k Golang : Command line ticker to show work in progress
+20.7k nginx: [emerg] unknown directive "passenger_enabled"
+5.8k PHP : Convert string to timestamp or datestamp before storing to database(MariaDB/MySQL)
+24.8k Golang : How to validate URL the right way
+25.6k Golang : Convert long hexadecimal with strconv.ParseUint example
+13.7k Facebook PHP getUser() returns 0
+6.1k Golang : Extract unicode string from another unicode string example
+5.1k Google : Block or disable caching of your website content
+10.4k Golang : Check a web page existence with HEAD request example
+23.8k Golang : minus time with Time.Add() or Time.AddDate() functions to calculate past date