<!--
{
  "availability" : [
    "iOS: 2.0.0 - 2.0.0",
    "iPadOS: 2.0.0 - 2.0.0",
    "tvOS: 9.0.0 - 9.0.0",
    "visionOS: 1.0.0 - 1.0.0",
    "watchOS: 2.0.0 - 2.0.0"
  ],
  "documentType" : "symbol",
  "framework" : "Foundation",
  "identifier" : "/documentation/Foundation/NSString/getCString(_:maxLength:)",
  "metadataVersion" : "0.1.0",
  "role" : "Instance Method",
  "symbol" : {
    "kind" : "Instance Method",
    "modules" : [
      "Foundation"
    ],
    "preciseIdentifier" : "c:objc(cs)NSString(im)getCString:maxLength:"
  },
  "title" : "getCString(_:maxLength:)"
}
-->

# getCString(_:maxLength:)

Invokes [`getCString(_:maxLength:range:remaining:)`](/documentation/Foundation/NSString/getCString(_:maxLength:range:remaining:)) with `maxLength` as the maximum length in char-sized units, the receiver’s entire extent as the range, and `NULL` for the remaining range.

```
func getCString(_ bytes: UnsafeMutablePointer<CChar>, maxLength: Int)
```

## Discussion

`buffer` must be large enough to contain `maxLength`  chars plus a terminating zero char (which this method adds).

Raises an `NSCharacterConversionException` if the receiver can’t be represented in the default C-string encoding without loss of information. Use [`canBeConverted(to:)`](/documentation/Foundation/NSString/canBeConverted(to:)) if necessary to check whether a string can be losslessly converted to the default C-string encoding. If it can’t, use [`lossyCString()`](/documentation/Foundation/NSString/lossyCString()) or [`data(using:allowLossyConversion:)`](/documentation/Foundation/NSString/data(using:allowLossyConversion:)) to get a C-string representation with some loss of information.

## See Also

[`func cString(using: UInt) -> UnsafePointer<CChar>?`](/documentation/Foundation/NSString/cString(using:))

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

[`var utf8String: UnsafePointer<CChar>?`](/documentation/Foundation/NSString/utf8String)

A null-terminated UTF8 representation of the string.

[`func getCString(UnsafeMutablePointer<CChar>, maxLength: Int, encoding: UInt) -> Bool`](/documentation/Foundation/NSString/getCString(_:maxLength:encoding:))

Converts the string to a given encoding and stores it in a buffer.



---

Copyright &copy; 2026 Apple Inc. All rights reserved. | [Terms of Use](https://www.apple.com/legal/internet-services/terms/site.html) | [Privacy Policy](https://www.apple.com/privacy/privacy-policy)