views:

803

answers:

2

I wonder which method would be better to convert const char* string to NSString.
I found there are some facts.

  • [NSString stringWithCString:length:] is kind of deprecated.
  • [NSString stringWithCString:encoding] may be used for my purpose

But I want to convert with length AND encoding(because I want to make that fine if I have some Non-ASCII character by setting encoding to UTF-8). Any thoughts?

I just think now

  1. create other char and copy with length by using std::strncpy(ch1, ch2, len)
  2. use [NSString stringWithCString:encoding:]

But it doesn't work well.

+8  A: 

Use [NSString initWithBytes:length:encoding].

Dietrich Epp
+1  A: 

If your const char* variable is named foo (and it points to a null-terminated string), just say

[NSString stringWithUTF8String:foo]

Because UTF-8 is a superset of ASCII, this will work whether foo points to UTF-8 or ASCII. Then you can move up to full Unicode with no problems.

Jon Reid
This only works if your string is ASCII, though. If your string is anything else (e.g. MacRoman or ISO Latin), you'll at best get the wrong glyph displayed for a particular character, at worst you'll get a NIL string because you happened to generate an invalid sequence of bytes that doesn't map to a valid UTF8 character (Yes, that's possible. UTF8 encodes way more than 256 different characters, so there are multi-byte sequences that encode a character, and some of these aren't valid (yet).
uliwitness