Initializer

init(cString:)

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

Declaration

init(cString: UnsafePointer<CChar>)

Parameters

cString

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

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�"

Relationships

From Protocol

See Also

Converting a C String

init?(bytesNoCopy: UnsafeMutableRawPointer, length: Int, encoding: String.Encoding, freeWhenDone: Bool)

Produces an initialized String object that contains a given number of bytes from a given buffer of bytes interpreted in a given encoding, and optionally frees the buffer. WARNING: this initializer is not memory-safe!

init(cString: UnsafePointer<UInt8>)

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

init?(cString: UnsafePointer<CChar>, encoding: String.Encoding)

Produces a string containing the bytes in a given C array, interpreted according to a given encoding.

init<Encoding>(decodingCString: UnsafePointer<Encoding.CodeUnit>, as: Encoding.Type)

Creates a string from the null-terminated sequence of bytes at the given pointer.

static func decodeCString<Encoding>(UnsafePointer<Encoding.CodeUnit>?, as: Encoding.Type, repairingInvalidCodeUnits: Bool) -> (result: String, repairsMade: Bool)?

Creates a new string by copying the null-terminated data referenced by the given pointer using the specified encoding.