Create an NSString from a char array with \ 0 characters in it?

I am trying to initialize a simple NSString from an unsigned array of char (ASCII encoded). The problem is that there are several \0 in the array as delimiters. If i use

 [[NSString alloc] initWithBytes:bytes length:length encoding:NSASCIIEncoding]; 

I get only a part before the first \0 . Is there a way to get the number of bytes specified in the length parameter, even if there is \0 s?

+4
source share
1 answer

The whole array fits into the string, it's just that when you try to display it, only the part to the initial \0 displayed.

Here is the code illustrating this point:

 unsigned char data[] = "hello\0world"; NSString *str = [[NSString alloc] initWithBytes:data length:sizeof(data) encoding:NSASCIIStringEncoding]; NSLog(@"%@", str); NSLog(@"%@", [str substringFromIndex:6]); 

The result is the following log output:

 hello world 
+5
source

All Articles