Human Cyborg Relations
Human Cyborg Relations

Reputation: 1244

Inserting a character in String (Swift)

I have a String "000". I want to change this to "0.00".

I took a look at the insert function.

var str = "000"
str.insert(".", at: str.endIndex)

How do I get the index of 2 before the end index?

I tried:

str.insert(".", at: str.endIndex - 1)

but this didn't work at all.

Upvotes: 2

Views: 4683

Answers (2)

Elserafy
Elserafy

Reputation: 61

Since Swift 2, String does no longer conform to SequenceType. In other words, you can not iterate through a string with a for...in loop.

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)

I remember when I tried to index into String without using any conversion. I was really frustrated that I couldn’t come up with or reach a desired result, and was about to give up. But I ended up creating my own workaround solution, and 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"
car[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!

Upvotes: 1

Marmelador
Marmelador

Reputation: 1017

You could also use Strings character property. Its basically an array made up of all the characters (duh) in the String.

So you would:

var str = "000"

let index = str.characters.index(str.characters.startIndex, offsetBy: 1)  //here you define a place (index) to insert at
str.characters.insert(".", at: index)  //and here you insert

Unfortunately you have to create an index first, as .insert does not allow you to specify the position using an Int.

Upvotes: 1

Related Questions