70

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?

2
  • did yo try this? stringts.insert("(", atIndex: 0) Commented Nov 24, 2014 at 11:34
  • it gives me an error: Type: 'String.index' does not conform to protocol 'IntegerLiteralConvertible' Commented Nov 24, 2014 at 11:45

11 Answers 11

99

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.

Sign up to request clarification or add additional context in comments.

Comments

53

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

4 Comments

You should not do that, because if your string contains Unicode characters you do not expect, you might be inserting stuff in the middle of grapheme clusters. Instead, look at how you are obtaining your indices and make them String.Index-friendly in order to design an Unicode-friendly flow...
Edit the answer for swift 3
The question was about Swift which has its own String. Do you for example answer each objective-c question with C code? Downvoted
how to remove the first element from NSMutableString
12
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.

3 Comments

Why is this an accepted answer? what is "advance"? This is not a working code
@breakline fixed.
is less than or equal, no? if it is bigger, you will have a crash.
9

Maybe this extension for Swift 4 will help:

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

6 Comments

Please explain your lines of code so other users can understand its functionality. Thanks!
What he (@IgnacioAra) said ! ^^^^^ Plus.. the code you provided is wrong. See my answer below.
@IgnacioAra I've just replaced String.Index parameter of native insert function into Integer, for easy to use.
@Dilapidus I've tested my code, there is no any issue. It works as I wish. What's wrong? I've seen your answer there is no any difference between yours and mine.
Hi @DilmuratAbduqayyum you are indexing against the string passed in, not self. For me your code barfed immediately since ind is almost always bigger than the length of the string passed in. Notice I replaced string in string.index and string.startIndex with self.
|
6

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

Comments

6

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
}

Comments

5

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.

Comments

4

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.

Comments

2

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

Comments

1

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!

Comments

-2
  • here it is my answer. - how to add one string into another string - at any given index - using for loop and prefix suffix -
let a  = "manchester"
let b = "hello"

var c = ""

c = "\(a.prefix(a.description.count/2)) \(b) \(a.suffix(a.description.count/2))"
        
        print(c)

output - 
manch hello ester

    

3 Comments

How would this add one string into another string at any given index? This only add it to the middle of the other string, and currently it doesn't have a way to specify the index.
currently its adding one string to middle of the other string. if you know the exact index number you can specify it after prefix .
Then you should consider using the index directly in your example code, instead of using a.description.count / 2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.