MyString = "CfegoAsZEM/sPu{10}u{10}}"
MyString.replacingOccurrences(of: """, with: "")
with print(MyString) I got this : "CfegoAsZEM/sP"
(that’s what I need)
with po MyString (on the debugger) : "CfegoAsZEM/sPu{10}u{10}}"
MyString = "CfegoAsZEM/sPu{10}u{10}}"
MyString.replacingOccurrences(of: """, with: "")
with print(MyString) I got this : "CfegoAsZEM/sP"
(that’s what I need)
with po MyString (on the debugger) : "CfegoAsZEM/sPu{10}u{10}}"
2
Answers
u{10}
is a linefeed characterMaybe a better way is to
trim
the string, it removes all whitespace and newline characters from the beginning and the end of the stringYour string doesn’t contain literal backslash characters. Rather, the
u{}
sequence is an escaped sequence that introduces a Unicode character. This is why you can’t remove it usingreplacingOccurrences
.In this case, as Vadian pointed out it is the "new line" character (0x10). Since this is an invisible "white space" character you don’t see it when you
print
the string, but you do see it when you usepo
. The debugger shows you escape sequences for non-printable characters. You will also see the sequence if youprint(MyString.debugDescription)
Unfortunately the
trimmingCharactersIn
function doesn’t appear to consider Unicode sequences.We can use the
filter
function to examine each character in the string. If the character is ASCII and has a value greater than 31 ( 32 is the space character, the first "printable" character in the ASCII sequence) we can include it. We also need to ensure that values that aren’t ASCII are included so as not to strip printable Unicode characters (e.g. emoji or non-Latin characters).Output
asciiValue
returns an optional, which isnil
if the character isn’t plain ASCII. I have used a nil-coalescing operator to return 32 in this case so that the character isn’t filtered.I modified the initial string to include some printable Unicode to demonstrate that it isn’t stripped by the filter.