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

IosStringSwiftInsert

Ios Problem Overview


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?

Ios Solutions


Solution 1 - Ios

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.

Solution 2 - Ios

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))

Solution 3 - Ios

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.

Solution 4 - Ios

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) )
  }
}

Solution 5 - Ios

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
}

Solution 6 - Ios

> 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

Solution 7 - Ios

You can't, because in Swift string indices (String.Index) is defined in terms of Unicode grapheme clusters, so that it handles all the Unicode stuff nicely. So you cannot construct a String.Index from an index directly. You can use advance(theString.startIndex, 3) to look at the clusters making up the string and compute the index corresponding to the third cluster, but caution, this is an O(N) operation.

In your case, it's probably easier to use a string replacement operation.

Check out this blog post for more details.

Solution 8 - Ios

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.

Solution 9 - Ios

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

Solution 10 - Ios

The simple and easy way is to convert String to Array to get the benefit of the index just like that:

let input = Array(str)

If you try to index into String without using any conversion.

Here is the full code of the extension:

extension String {
    subscript (_ index: Int) -> String {
    
        get {
             String(self[self.index(startIndex, offsetBy: index)])
        }
    
        set {
            if index >= count {
                insert(Character(newValue), at: self.index(self.startIndex, offsetBy: count))
            } else {
                insert(Character(newValue), at: self.index(self.startIndex, offsetBy: index))
            }
        }
    }
}

Now that you can read and write a single character from string using its index just like you originally wanted to:

var str = "car"
str[3] = "d"
print(str)

It’s simple and useful way to use it and get through Swift’s String access model. Now that you’ll feel it’s smooth sailing next time when you can loop through the string just as it is, not casting it into Array.

Try it out, and see if it can help!

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionlakshmenView Question on Stackoverflow
Solution 1 - IosDan BeaulieuView Answer on Stackoverflow
Solution 2 - IosDharmesh KheniView Answer on Stackoverflow
Solution 3 - IosEricView Answer on Stackoverflow
Solution 4 - IosMurat UygarView Answer on Stackoverflow
Solution 5 - IosManinderjit SinghView Answer on Stackoverflow
Solution 6 - IosElvinMView Answer on Stackoverflow
Solution 7 - IosThomas DeniauView Answer on Stackoverflow
Solution 8 - IosDilapidusView Answer on Stackoverflow
Solution 9 - IosPranavan SPView Answer on Stackoverflow
Solution 10 - IosElserafyView Answer on Stackoverflow