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
+20.9k Golang : Sort and reverse sort a slice of strings
+13.6k Golang : unknown escape sequence error
+36.1k Golang : Convert(cast) int64 to string
+8.3k Linux/Unix : fatal: the Postfix mail system is already running
+7.1k Golang : Calculate how many weeks left to go in a given year
+11.7k Golang : Clean formatting/indenting or pretty print JSON result
+18.2k Golang : Example for RSA package functions
+22.4k Golang : Strings to lowercase and uppercase example
+14.9k JavaScript/JQuery : Detect or intercept enter key pressed example
+10.9k Golang : Roll the dice example
+21.5k Golang : Setting up/configure AWS credentials with official aws-sdk-go
+25k Golang : Get current file path of a file or executable