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.
CodePudding user response:
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.
CodePudding user response:
You can do some pointer operations and use the init(cString:)
initialiser, which takes a null terminated string.
let resultString = data.withUnsafeBytes { buffer in
guard let pointer = buffer.baseAddress?.assumingMemoryBound(to: CChar.self) else {
return ""
}
return String(cString: pointer)
}