How to add a character at a particular index in string in Swift

后端 未结 9 1335
自闭症患者
自闭症患者 2020-12-14 05:30

I have a string like this in Swift:

var stringts:String = \"3022513240\"

If I want to change it to string to something like this: \"(

相关标签:
9条回答
  • 2020-12-14 06:01

    Swift 4.2 version of Dilmurat's answer (with code fixes)

    extension String {
        mutating func insert(string:String,ind:Int) {
            self.insert(contentsOf: string, at:self.index(self.startIndex, offsetBy: ind) )
        }
    }
    

    Notice if you will that the index must be against the string you are inserting into (self) and not the string you are providing.

    0 讨论(0)
  • 2020-12-14 06:08

    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))
    
    0 讨论(0)
  • 2020-12-14 06:08

    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

    0 讨论(0)
  • 2020-12-14 06:11

    Swift 3

    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.

    0 讨论(0)
  • 2020-12-14 06:13

    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) )
      }
    }
    
    0 讨论(0)
  • 2020-12-14 06:18

    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
    
    0 讨论(0)
提交回复
热议问题