Sunday, May 12, 2013

NSString stringWithCString encoding example ios

stringWithCString: encoding:

Returns a string containing the bytes in a given C array, interpreted according to a given encoding.
+ (id)stringWithCString:(const char *)cString encoding:(NSStringEncoding)enc
A C array of bytes. The array must end with a NULL character; intermediate NULL characters are not allowed.
The encoding of cString.
Return Value of [ NSString stringWithCString encoding ]
A string containing the characters described in cString.
If cString is not a NULL-terminated C string, or encoding does not match the actual encoding, the results are undefined.
Example of [ NSString stringWithCString encoding ]
- (NSString *) platform{
    size_t size;
    sysctlbyname("hw.machine", NULL, &size, NULL, 0);
    char *machine = malloc(size);
    sysctlbyname("hw.machine", machine, &size, NULL, 0);
    NSString *platform = [NSString stringWithCString:machine encoding:NSASCIIStringEncoding];
    return platform;

Example of [ NSString stringWithCString encoding ]
const *char cString = "Hello";
NSString *myNSString = [NSString stringWithCString:cString encoding:NSASCIIStringEncoding];
Example of [ NSString stringWithCString encoding ]
const char* hardString = "Hello, World";
    char *buffer = nil;

    buffer = calloc(13, 1);
    bzero(buffer, 13);

    memcpy(buffer, hardString, 12);

    NSString *aString = [NSString stringWithCString:buffer encoding:NSUTF8StringEncoding];        
    NSLog(@"aString: %@  \t filled buffer:(%p) [%s]", aString, (void*)buffer, buffer);

    bzero(buffer, 13); 
    NSLog(@"aString: %@  \t zeroed buffer:(%p) [%s]", aString, (void*)buffer, buffer);

    NSLog(@"aString: %@  \t free'd buffer:(%p)", aString, (void*)buffer);

    buffer = nil;        
    NSLog(@"aString: %@  \t nulled buffer:(%p)", aString, (void*)buffer);