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
+19k Golang : Get ASCII code from a key press(cross-platform) example
+17.3k Golang : Convert date string to variants of time.Time type examples
+9.5k CodeIgniter : How to check if a session exist in PHP?
+15.5k Golang : Logging with logrus
853 Golang : PGX CopyFrom to insert rows into Postgres database
+16.5k Golang : Clean up null characters from input data
+12.6k Golang : Read integer from file into array
+7k Golang : How to control fmt or log print format?
+6.4k Golang : Handle sub domain with Gin
+9.7k Golang : Encrypt and decrypt data with x509 crypto
+24.1k Golang : Convert integer to binary, octal, hexadecimal and back to integer
+12.5k Golang : How to check for empty array string or string?