Instance Method

cString(using:)

Returns a representation of the receiver as a C string using a given encoding.

Declaration

func cString(using encoding: UInt) -> UnsafePointer<Int8>?

Parameters

encoding

The encoding for the returned C string. For possible values, see NSStringEncoding.

Return Value

A C string representation of the receiver using the encoding specified by encoding. Returns NULL if the receiver cannot be losslessly converted to encoding.

Discussion

The returned C string is guaranteed to be valid only until either the receiver is freed, or until the current memory is emptied, whichever occurs first. You should copy the C string or use getCString(_:maxLength:encoding:) if it needs to store the C string beyond this time.

You can use canBeConverted(to:) to check whether a string can be losslessly converted to encoding. If it can’t, you can use data(using:allowLossyConversion:) to get a C-string representation using encoding, allowing some loss of information (note that the data returned by data(using:allowLossyConversion:) is not a strict C-string since it does not have a NULL terminator).

Special Considerations

UTF-16 and UTF-32 are not considered to be C string encodings, and should not be used with this method—the results of passing NSUTF16StringEncoding, NSUTF32StringEncoding, or any of their variants are undefined.

See Also

Getting C Strings

func getCString(UnsafeMutablePointer<Int8>, maxLength: Int, encoding: UInt)

Converts the receiver’s content to a given encoding and stores them in a buffer.

var utf8String: UnsafePointer<Int8>?

A null-terminated UTF8 representation of the string.