How do I convert a NSString into a std::string?

Objective CObjective C++

Objective C Problem Overview


I have an NSString object and want to convert it into a std::string.

How do I do this in Objective-C++?

Objective C Solutions


Solution 1 - Objective C

NSString *foo = @"Foo";
std::string bar = std::string([foo UTF8String]);

Edit: After a few years, let me expand on this answer. As rightfully pointed out, you'll most likely want to use cStringUsingEncoding: with NSASCIIStringEncoding if you are going to end up using std::string. You can use UTF-8 with normal std::strings, but keep in mind that those operate on bytes and not on characters or even graphemes. For a good "getting started", check out this question and its answer.

Also note, if you have a string that can't be represented as ASCII but you still want it in an std::string and you don't want non-ASCII characters in there, you can use dataUsingEncoding:allowLossyConversion: to get an NSData representation of the string with lossy encoded ASCII content, and then throw that at your std::string

Solution 2 - Objective C

As Ynau's suggested in the comment, in a general case it would be better to keep everything on the stack instead of heap (using new creates the string on the heap), hence (assuming UTF8 encoding):

NSString *foo = @"Foo";
std::string bar([foo UTF8String]);

Solution 3 - Objective C

As noted on philjordan.eu it could also be that the NSString is nil. In such a case the cast should be done like this:

> // NOTE: if foo is nil this will produce an empty C++ string > > // instead of dereferencing the NULL pointer from UTF8String.

This would lead you to such a conversion:

NSString *foo = @"Foo";
std::string bar = std::string([foo UTF8String], [foo lengthOfBytesUsingEncoding:NSUTF8StringEncoding]);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiongaborView Question on Stackoverflow
Solution 1 - Objective CJustSidView Answer on Stackoverflow
Solution 2 - Objective CMarco83View Answer on Stackoverflow
Solution 3 - Objective CBruno BieriView Answer on Stackoverflow