How to move all special characters to the beginning of a string in Swift

1 Answer

0 votes
import Foundation

func moveSpecialCharactersToBeginning(_ s: String) -> String {
    let specials = s.filter { !($0.isLetter || $0.isNumber || $0.isWhitespace) }
    let chars    = s.filter { $0.isLetter || $0.isNumber || $0.isWhitespace }
    
    return String(specials + chars)
}

let s = "c++20$c&^java*(rust) php <>/python 3.14.2"

print(moveSpecialCharactersToBeginning(s))



/*
run:

++$&^*()<>/..c20cjavarust php python 3142

*/

 



answered Dec 12, 2025 by avibootz

Related questions

...