How to delete a character at an integer index from a string

Sorry to ask this first-grader question, but what is the best way to delete a character at a given integer index from a string if the character exists at that index?

var u = "occurRence" // i in 0..<u.count

// possible
var delete = "R"
let i = 5

// possible
var delete = "e"
let i = 6

// not possible
var delete = "e"
let i = 0


1 Like

These kinds of String index operations can be kind of annoying in Swift, so it's perfectly understandable to ask that question. Here's how I would implement that:

extension String {
  mutating func removeIfExists(_ character: Character, at index: Int) {
    let indices = Array(indices)
    guard index < indices.count else {
      return
    }

    let stringIndex = indices[index]
    let characterAtIndex = self[stringIndex]
    guard characterAtIndex == character else {
      return
    }

    remove(at: stringIndex)
  }
}

First I get the array of possible indices we can use to index the string. Then I check that the index given by the caller is valid, and convert the integer index into a string index. Then I check that the character at that index matches the specified character. Finally if that check succeeds I remove the character at the specified index.

Hopefully that helps, feel free to ask for clarification if any of that doesn't make sense.

2 Likes

You don't need to create an Array. For indexing operations, use the index(...) family of methods.

extension String {
  mutating func removeIfExists(_ character: Character, at offset: Int) {
    if let i = index(startIndex, offsetBy: offset, limitedBy: endIndex), 
      i < endIndex,
      self[i] == character {
      remove(at: i)
    }
  }
}
6 Likes