mick
mick

Reputation: 45

NSString to char[]?

struct DATA
{
    unsigned char USERNAME[32];
};

i want copy a NSString to struct DATA.USERNAME , how to do it ?

Upvotes: 0

Views: 2837

Answers (2)

Chuck
Chuck

Reputation: 237110

You first need to know what encoding is expected. NSString can generate bytes in a wide range of encodings. Then you pass a pointer to the USERNAME array to getCString:maxLength:encoding:. So, for example, if you want to copy the contents of the NSString myCocoaString as UTF-8 into USERNAME field of a DATA struct called myData, you'd do:

BOOL success = [myCocoaString getCString:myData.USERNAME maxLength:32 encoding:NSUTF8StringEncoding];
NSLog(@"Was %@ to store string contents in USERNAME!", success ? @"able" : @"not able");

Upvotes: 0

Grant Paul
Grant Paul

Reputation: 5902

You can use the -[NSString UTF8String] method to get a C string of your NSString. Then, you can use strncpy(DATA.USERNAME, [mystring UTF8String], 32); to copy that string into the structure.

Upvotes: 2

Related Questions