How to remove the last word from a string in Swift

2 Answers

0 votes
import Foundation

func removeLastWord(from input: String) -> String {
    if let lastSpaceRange = input.range(of: " ", options: .backwards) {
        return String(input[..<lastSpaceRange.lowerBound])
    } else {
        return input // No space found, return original
    }
}

let s = "c# swift c c++ java"

let result = removeLastWord(from: s)

print(result)



/*
run:

c# swift c c++

*/

 



answered Sep 24, 2025 by avibootz
0 votes
import Foundation

func removeLastWord(_ s: String) -> String {
    let trimmed = s.trimmingCharacters(in: .whitespaces)

    guard let range = trimmed.range(of: " ", options: .backwards) else {
        return trimmed   // no space → return original
    }

    return String(trimmed[..<range.lowerBound])
}

func main() {
    var s: String

    s = "c c++ c# java python"
    print("1. \(removeLastWord(s))")

    s = ""
    print("2. \(removeLastWord(s))")

    s = "c"
    print("3. \(removeLastWord(s))")

    s = "c# java python "
    print("4. \(removeLastWord(s))")

    s = "  "
    print("5. \(removeLastWord(s))")
}

main()


/*
run:

1. c c++ c# java
2. 
3. c
4. c# java
5. 

*/

 



answered Mar 27 by avibootz
...