iHTCboy
iHTCboy

Reputation: 2797

Way converting char array into NSString object with one more in the end character

code:

const char sbyte[] = {65, 66};

NSLog(@"byte:%c", 66);
NSLog(@"byte:%c", 67);
NSLog(@"byte:%s", sbyte);

NSString *string1 = [[NSString alloc] initWithCString:sbyte encoding:NSUTF8StringEncoding];
NSLog(@"string1: %@", string1);

NSString *string2 = [NSString stringWithFormat:@"%s", sbyte];
NSLog(@"string2: %@", string2);

print:

 byte:B
 byte:C
 byte:ABb
 string1: ABb
 string2: ABb

The correct application is 'AB', but now it is 'ABb', one more character 'b'??

thanks!

Upvotes: 0

Views: 50

Answers (1)

Sulthan
Sulthan

Reputation: 130210

All C strings have to be zero terminated:

const char sbyte[] = {65, 66, 0};

They don't contain any length information therefore the zero is a way to detect end of data.

Upvotes: 3

Related Questions