Contents

init(cString:)

Creates a new string by copying the null-terminated UTF-8 data referenced by the given pointer.

Declaration

init(cString nullTerminatedUTF8: UnsafePointer<CChar>)

Parameters

  • nullTerminatedUTF8:

    A pointer to a null-terminated sequence of UTF-8 code units.

Discussion

If cString contains ill-formed UTF-8 code unit sequences, this initializer replaces them with the Unicode replacement character ("\u{FFFD}").

The following example calls this initializer with pointers to the contents of two different CChar arrays—the first with well-formed UTF-8 code unit sequences and the second with an ill-formed sequence at the end.

let validUTF8: [CChar] = [67, 97, 102, -61, -87, 0]
validUTF8.withUnsafeBufferPointer { ptr in
    let s = String(cString: ptr.baseAddress!)
    print(s)
}
// Prints "Café"

let invalidUTF8: [CChar] = [67, 97, 102, -61, 0]
invalidUTF8.withUnsafeBufferPointer { ptr in
    let s = String(cString: ptr.baseAddress!)
    print(s)
}
// Prints "Caf�"

See Also

Converting a C String