Question

Currently I'm working on an iOS application, in which I need to convert a NSString to char *. For this I used the following code:

NSString *str = @"Hello ! How Are You ???";
char *as = (char *)[[str dataUsingEncoding:NSUTF8StringEncoding] bytes];
int a = strlen(as);
NSLog(@"Length using: -length  : [%d]",[str length]);
NSLog(@"Length using: strlen() : [%d]",a);

But the issue is I got different lengths.

Output:

Length using: -length  : [23]
Length using: strlen() : [33]

I checked it again and again. But sometimes I get correct output. But most of the time I got the wrong result.

What is the issue ? Is there any mistake in my code ?

Please help me, thanks in advance

Était-ce utile?

La solution

It looks like dataUsingEncoding: does not include '\0' at the end and strlen relies on it. use char *as = (char *)[str cStringUsingEncoding:NSUTF8StringEncoding]; instead. it gives correct results.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top