How to remove N characters from the middle of a string in Swift

3 Answers

0 votes
import Foundation

func removeMiddleCharacters(from str: String, count n: Int) -> String {
    guard n > 0 && n < str.count else { return str }
    
    let middleIndex = str.index(str.startIndex, offsetBy: str.count / 2)
    let startIndex = str.index(middleIndex, offsetBy: -(n / 2))
    let endIndex = str.index(startIndex, offsetBy: n)
    
    var modifiedString = str
    modifiedString.removeSubrange(startIndex..<endIndex)
    
    return modifiedString
}

let str = "abc123def"
let resultString = removeMiddleCharacters(from: str, count: 3)

print(resultString)  



/*
run:

abcdef

*/

 



answered Apr 20, 2025 by avibootz
0 votes
import Foundation

func removeMiddleCharacters(from str: String, count n: Int) -> String {
    guard n > 0 && n < str.count else { return str }
    
    let middleIndex = str.count / 2
    let startIndex = middleIndex - (n / 2)
    let endIndex = startIndex + n
    
    let prefix = str.prefix(startIndex)
    let suffix = str.suffix(str.count - endIndex)
    
    return String(prefix) + String(suffix)
}

let str = "abc123def"
let resultString = removeMiddleCharacters(from: str, count: 3)

print(resultString)  



/*
run:

abcdef

*/

 



answered Apr 20, 2025 by avibootz
0 votes
import Foundation

func removeMiddleCharacters(from str: String, count n: Int) -> String {
    guard n > 0 && n < str.count else { return str }
    
    let middleIndex = str.count / 2
    let startIndex = middleIndex - (n / 2)
    let endIndex = startIndex + n
    
    let range = str.index(str.startIndex, offsetBy: startIndex)..<str.index(str.startIndex, offsetBy: endIndex)
    
    var modifiedString = str
    modifiedString.removeSubrange(range)
    
    return modifiedString
}

let str = "abc123def"
let resultString = removeMiddleCharacters(from: str, count: 3)

print(resultString)  



/*
run:

abcdef

*/

 



answered Apr 20, 2025 by avibootz
...