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
+5.2k Golang : Get S3 or CloudFront object or file information
+5.1k Golang : Calculate half life decay example
+5.3k Python : Print unicode escape characters and string
+17.7k Golang : Get all upper case or lower case characters from string example
+8k Golang : Metaprogramming example of wrapping a function
+30.6k Golang : Interpolating or substituting variables in string examples
+19.6k Golang : Append content to a file
+13.5k Golang : Check if an integer is negative or positive
+6.1k Golang : How to search a list of records or data structures
+30.2k Golang : How to redirect to new page with net/http?
+12.4k Golang : Send data to /dev/null a.k.a blackhole with ioutil.Discard
+8.2k Golang: Prevent over writing file with md5 hash