How to remove the middle word from a string in Swift

1 Answer

0 votes
import Foundation

func removeMiddleWord(_ str: String) -> String {
    // Split the string into words
    let words = str.split(separator: " ")
    
    // Calculate the middle index
    let middleIndex = words.count / 2
    
    // Create a new string without the middle word
    let result = words[0..<middleIndex] + words[(middleIndex + 1)..<words.count]
    
    return result.joined(separator: " ")
}

let str = "swift c c++ java rust"

print(removeMiddleWord(str))



/*
run:
 
swift c java rust
 
*/

 



answered Dec 4, 2024 by avibootz
...