tksohishi
tksohishi

Reputation: 245

Convert const char* string to NSString with length AND encoding

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

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.

Upvotes: 18

Views: 32768

Answers (2)

Dietrich Epp
Dietrich Epp

Reputation: 213847

Use:

[NSString initWithBytes:length:encoding].

Upvotes: 17

Jon Reid
Jon Reid

Reputation: 20980

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.

Upvotes: 46

Related Questions