How to add a character at a particular index in st

2019-01-23 00:45发布

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?

8条回答
时光不老,我们不散
2楼-- · 2019-01-23 01:24

You can't use in below Swift 2.0 because String stopped being a collection in Swift 2.0. but in Swift 3 / 4 is no longer necessary now that String is a Collection again. Use native approach of String,Collection.

var stringts:String = "3022513240"
let indexItem = stringts.index(stringts.endIndex, offsetBy: 0)
stringts.insert("0", at: indexItem)
print(stringts) // 30225132400
查看更多
我命由我不由天
3楼-- · 2019-01-23 01:25

To Display 10 digit phone number into USA Number format (###) ###-#### SWIFT 3

func arrangeUSFormat(strPhone : String)-> String {
    var strUpdated = strPhone
    if strPhone.characters.count == 10 {
        strUpdated.insert("(", at: strUpdated.startIndex)
        strUpdated.insert(")", at: strUpdated.index(strUpdated.startIndex, offsetBy: 4))
        strUpdated.insert(" ", at: strUpdated.index(strUpdated.startIndex, offsetBy: 5))
        strUpdated.insert("-", at: strUpdated.index(strUpdated.startIndex, offsetBy: 9))
    }
    return strUpdated
}
查看更多
祖国的老花朵
4楼-- · 2019-01-23 01:26

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)
查看更多
我只想做你的唯一
5楼-- · 2019-01-23 01:30
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 bigger than or equal to the size of the string, otherwise you'll get a crash.

查看更多
一纸荒年 Trace。
6楼-- · 2019-01-23 01:32

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

查看更多
Luminary・发光体
7楼-- · 2019-01-23 01:34

Maybe this extension for Swift 4 will help:

extension String {
    mutating func insert(string:String,ind:Int) {
        self.insert(contentsOf: string, at:string.index(string.startIndex, offsetBy: ind) )
    }
}
查看更多
登录 后发表回答