How to add a character at a particular index in string in Swift
Swift 3
Use the native Swift approach:
var welcome = "hello"welcome.insert("!", at: welcome.endIndex) // prints hello!welcome.insert("!", at: welcome.startIndex) // prints !hellowelcome.insert("!", at: welcome.index(before: welcome.endIndex)) // prints hell!owelcome.insert("!", at: welcome.index(after: welcome.startIndex)) // prints h!ellowelcome.insert("!", at: welcome.index(welcome.startIndex, offsetBy: 3)) // prints hel!lo
If you are interested in learning more about Strings and performance, take a look at @Thomas Deniau's answer down below.
If you are declaring it as NSMutableString
then it is possible and you can do it this way:
let str: NSMutableString = "3022513240)"str.insert("(", at: 0)print(str)
The output is :
(3022513240)
EDIT:
If you want to add at starting:
var str = "3022513240)"str.insert("(", at: str.startIndex)
If you want to add character at last index:
str.insert("(", at: str.endIndex)
And if you want to add at specific index:
str.insert("(", at: str.index(str.startIndex, offsetBy: 2))
var myString = "hell"let index = 4let character = "o" as CharactermyString.insert( character, at: myString.index(myString.startIndex, offsetBy: index))print(myString) // "hello"
Careful: make sure that index
is smaller than or equal to the size of the string, otherwise you'll get a crash.