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
+14k Javascript : Prompt confirmation before exit
+16.3k Golang : Get IP addresses of a domain name
+20k Golang : How to get struct tag and use field name to retrieve data?
+19.7k Golang : Accept input from user with fmt.Scanf skipped white spaces and how to fix it
+10k Golang : Get login name from environment and prompt for password
+5.7k CodeIgniter/PHP : Remove empty lines above RSS or ATOM xml tag
+8k Golang : Randomize letters from a string example
+10.4k Android Studio : Simple input textbox and intercept key example
+12k Golang : Decompress zlib file example
+8.9k Golang : Capture text return from exec function example
+5.3k Python : Delay with time.sleep() function example