简体   繁体   中英

Replacing \\ with \ in Swift

I have a requirement where I want to replace "\\\\" with "\\" however it does not seem to work.

var st = "satya\\"
st = st.replacingOccurrences(of: "\\", with: "\", options: 
NSString.CompareOptions.literal,
range: nil)

You should escape the backslashes if you want to replace two backslashes with one.

st.replacingOccurrences(of: "\\\\", with: "\\", options: .literal, range: nil)

However, as @VTodorov mentioned, "satya\\\\" is actually stored as satya\\ , since you already escaped a backlash in it. If you want to store a string with two backslashes, you should write it as "satya\\\\\\\\" .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM