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
+12.6k Golang : Compress and decompress file with compress/flate example
+7.2k Your page has meta tags in the body instead of the head
+30.9k Golang : Convert []string to []byte examples
+9.1k Golang : How to tokenize source code with text/scanner package?
+16.2k Golang : Clone with pointer and modify value
+12.1k Golang : How to get a user home directory path?
+9.8k Golang : Natural string sorting example
+7k Findstr command the Grep equivalent for Windows
+16.1k Golang : When to use init() function?
+32.7k Golang : Proper way to set function argument default value
+11k Golang : List running EC2 instances and descriptions
+7.2k Golang : Emulate NumPy way of creating matrix example