I have a string like this in Swift:
var stringts:String = "3022513240"
If I want to change it to string to something like this: "(302)-251-3240"
, I want to add the partheses at index 0, how do I do it?
In Objective-C, it is done this way:
NSMutableString *stringts = "3022513240";
[stringts insertString:@"(" atIndex:0];
How to do it in Swift?
One can use the StringBuffer class method namely the insert() method to add character to String at the given position. This method inserts the string representation of given data type at given position in StringBuffer. Syntax: str.
for aCharacter: Character in aString { var str: String = "" var newStr: String = str. append(aCharacter) // ERROR ... }
To insert a character in string at specific index in Swift, use the String method String. insert() . where str1 is the string, ch is the character and i is the index of type String. Index.
To get index of a substring in a string with Swift 2: let text = "abc" if let range = text. rangeOfString("b") { var index: Int = text. startIndex.
Use the native Swift approach:
var welcome = "hello"
welcome.insert("!", at: welcome.endIndex) // prints hello!
welcome.insert("!", at: welcome.startIndex) // prints !hello
welcome.insert("!", at: welcome.index(before: welcome.endIndex)) // prints hell!o
welcome.insert("!", at: welcome.index(after: welcome.startIndex)) // prints h!ello
welcome.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 = 4
let character = "o" as Character
myString.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.
Maybe this extension for Swift 4 will help:
extension String {
mutating func insert(string:String,ind:Int) {
self.insert(contentsOf: string, at:self.index(self.startIndex, offsetBy: ind) )
}
}
var phone= "+9945555555"
var indx = phone.index(phone.startIndex,offsetBy: 4)
phone.insert("-", at: indx)
index = phone.index(phone.startIndex, offsetBy: 7)
phone.insert("-", at: indx)
//+994-55-55555
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