I would like to find out how to get a part of a string in Swift. I am looking for the Swift equivalents of the Mid$, Right$, and Left$ functions. Any help would be appreciated.
How to Find SubString in Swift? To find substring of a String in Swift, prepare Range object using start and end indices, then give this Range object to the string in square brackets as an index. The syntax to concatenate two strings is:
The syntax for string creation and manipulation is lightweight and readable, with a string literal syntax that’s similar to C. String concatenation is as simple as combining two strings with the + operator, and string mutability is managed by choosing between a constant or a variable, just like any other value in Swift.
Swift’s String and Character types provide a fast, Unicode-compliant way to work with text in your code.
Swift Substring. To find substring of a String in Swift, prepare range using start and end indexes, then use the range on the string. The syntax to concatenate two strings is: where startPosition and endPosition are integers that define the bounds of the substring in the main string str.
Swift 4, Swift5
Modern API has got this syntax:
let str = "Hello world!"
let prefix = String(str.prefix(1))
let suffix = String(str.suffix(1))
Edit: This answer was from 2014 and is obsolete today, I recommend referencing Vyacheslav's answer instead
The equivalent of Left is substringToIndex
Example: (directly from this site)
let myString = "ABCDEFGHI"
let mySubstring = (myString.substringToIndex(2))
//This grabs the first 2 digits of the string and stops there,
//which returns "AB"
The (rough) equivalent of Right is substringFromIndex
Example: (directly from the same site)
let myString = "ABCDEFGHI"
let mySubstring = (myString.substringFromIndex(2))
//This jumps over the first 2 digits of the string and grabs the rest,
//which returns "CDEFGHI"
See https://web.archive.org/web/20170504165315/http://www.learnswiftonline.com/reference-guides/string-reference-guide-for-swift/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With