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.9k Golang : Text file editor (accept input from screen and save to file)
+41.2k Golang : Convert string to array/slice
+15.3k Chrome : ERR_INSECURE_RESPONSE and allow Chrome browser to load insecure content
+26.3k Golang : Encrypt and decrypt data with AES crypto
+8.1k Golang: Prevent over writing file with md5 hash
+4.5k Linux/MacOSX : How to symlink a file?
+9.7k Golang : Get escape characters \u form from unicode characters
+5.6k CodeIgniter/PHP : Remove empty lines above RSS or ATOM xml tag
+3.1k Golang : Fix go-cron set time not working issue
+10.3k Golang : How to unmarshal JSON inner/nested value and assign to specific struct?
+12.7k Golang : Convert(cast) uintptr to string example
+31.9k Golang : Convert []string to []byte examples