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.2k Golang : Serving HTTP and Websocket from different ports in a program example
+5.3k PHP : Hide PHP version information from curl
+5.7k Python : Print unicode escape characters and string
+23.6k Golang : Read a file into an array or slice example
+10.4k Golang : How to check if a website is served via HTTPS
+10.3k Golang : Bcrypting password
+14.2k Javascript : Prompt confirmation before exit
+15.9k Golang : ROT47 (Caesar cipher by 47 characters) example
+29.9k Golang : How to get HTTP request header information?
+7.4k Golang : Not able to grep log.Println() output
+5.3k Python : Create Whois client or function example
+6.8k Golang : Get expvar(export variables) to work with multiplexer