Reputation: 107231
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
Upvotes: 0
Views: 440
Reputation: 1091
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.
Upvotes: 2