An iOS/Swift library delivers a Data object containing a null terminated string.
When converting it to a String by calling String(data: dataInstance, encoding: .utf8), the returned String ends with "\0".
Question now is, how do you convert the Data instance to a String without having "\0" appended? I.e. how can you omit the null terminating character at the end?
Trying to just .trimmingCharacters(in: .whitespacesAndNewlines) doesn’t have any effect, so your advise is very much appreciated. Thank you.
>Solution :
A possible solution: Determine the index of the terminating zero, and convert only the preceding part of the data:
let data = Data([65, 66, 0, 67, 0])
let end = data.firstIndex(where: { $0 == 0 }) ?? data.endIndex
if let string = String(data: data[..<end], encoding:.utf8) {
print(string.debugDescription) // "AB"
}
If the data does not contain a null byte then everything will be converted.