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
+6.4k Golang : Output or print out JSON stream/encoded data
+5k Golang : Qt update UI elements with core.QCoreApplication_ProcessEvents
+32.7k Delete a directory in Go
+11.2k Golang : Fuzzy string search or approximate string matching example
+5.3k Unix/Linux/MacOSx : Get local IP address
+13.9k Golang : Send email with attachment(RFC2822) using Gmail API example
+4.7k Golang : Get a list of crosses(instruments) available to trade from Oanda account
+9.6k Golang : Channels and buffered channels examples
+10.9k Golang : Fix fmt.Scanf() on Windows will scan input twice problem
+6.3k Golang : Warp text string by number of characters or runes example
+16.7k Golang : Find file size(disk usage) with filepath.Walk
+25.8k Golang : Convert(cast) string to uint8 type and back to string