String with null chars

I have a strange issue: Needed to transfer some data across devices.
The string content while debugging is like "\0\0\nABCDEF"

It should be just "ABCDEF"

I used trimmingCharacreters(in: whitespacesandNewlines)
but not much help. When printed, I do see 2 blank vertical line space and then ABCDEF

Appreciate any ideas on getting rid of those "\0\0\n" in front in a simple way...
Thanks in advance

Does this work for you?

let trimmedString = inputString.drop(while: { $0 == "\0" })

Try this:

let badString: NSString = "\0\0\nABCDEF"
let okString = badString.trimmingCharacters(in: CharacterSet.letters.inverted) // ABCDEF

Thanks to both. I tried trimmingCharacters(in: CharacterSet.letters.inverted) // ABCDEF

it worked. Had spent whole day debugging for these hidden chars :slight_smile:

Note that this will remove anything that isn't a letter. That is, numbers will also be trimmed out. It may be what you want, but you should be aware of it. There are other predefined character sets you can use, or you can create your own from a list of valid characters.

I think you're best off just using String.removeAll(where:). String.trimmingCharacters(in:) is relatively slow and unnecessarily complex for this purpose, and as mentioned above, it probably stomps on things you probably don't want to touch.

var str = "\0\0ABC"
str.removeAll { $0 == "\0" }
2 Likes