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.1k Golang : Write multiple lines or divide string into multiple lines
+5.2k PHP : Hide PHP version information from curl
+5.7k Golang : Find change in a combination of coins example
+4.9k Golang : micron to centimeter example
+14.4k Golang : Missing Bazaar command
+22.3k Golang : How to read JPG(JPEG), GIF and PNG files ?
+6k Golang : Get missing location after unmarshal binary and gob decode time.
+8.3k Golang : How to check variable or object type during runtime?
+7.6k Golang : Error reading timestamp with GORM or SQL driver
+13.6k Generate salted password with OpenSSL example
+13.5k Golang : Set image canvas or background to transparent
+15.4k Golang : Force download file example