skip to Main Content
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


  1. u{10} is a linefeed character

    Maybe a better way is to trim the string, it removes all whitespace and newline characters from the beginning and the end of the string

    let myString = "CfegoAsZEM/sPu{10}u{10}"
    let trimmedString = myString.trimmingCharacters(in: .whitespacesAndNewlines)
    
    Login or Signup to reply.
  2. Your 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 using replacingOccurrences.

    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 use po. The debugger shows you escape sequences for non-printable characters. You will also see the sequence if you print(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).

    let MyString = "CfegoAsZEM/sPu{10}u{13}$}๐Ÿ”…u{1F600}".filter { $0.asciiValue ?? 32 > 31 }
    print(MyString.debugDescription)
    print(MyString)
    

    Output

    "CfegoAsZEM/sP}๐Ÿ”…๐Ÿ˜€"

    CfegoAsZEM/sP}๐Ÿ”…๐Ÿ˜€

    asciiValue returns an optional, which is nil 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search