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
+9.4k Golang : How to delete element(data) from map ?
+31.3k Golang : Smarter Error Handling with strings.Contains()
+50.5k Golang : How to get time in milliseconds?
+32.8k Golang : How to stream file to client(browser) or write to http.ResponseWriter?
+5k Golang : Function as an argument type example
+23.9k Golang : Convert IP address string to long ( unsigned 32-bit integer )
+5.6k Golang : Humanize and Titleize functions
+15.4k Golang : Gzip file example
+4.8k Unix/Linux : How to test user agents blocked successfully ?
+13.2k Golang : Reset buffer example
+4.4k PHP : Fix Call to undefined function curl_init() error
+7.6k Android Studio : Indicate progression with ProgressBar example