How to convert NSString to std :: string?

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

How to do it in Objective-C ++?

+75
objective-c objective-c ++
Nov 03 '11 at 20:50
source share
3 answers
 NSString *foo = @"Foo"; std::string bar = std::string([foo UTF8String]); 

Edit: in a few years, let me expand on this answer. As rightly pointed out, you will most likely want to use cStringUsingEncoding: with NSASCIIStringEncoding if you intend to use std::string . You can use UTF-8 with regular std::strings , but keep in mind that they work with bytes, not characters or even graphemes. For a good β€œget started” check out this question and its answer .

Also note: if you have a string that cannot be represented as ASCII, but you still want it in std::string and you don't need non-ASCII characters, you can use dataUsingEncoding:allowLossyConversion: for retrieve a NSData representation of a string with ASCII content with lossy encoding, and then throw it into your std::string

+101
Nov 03 2018-11-11T00:
source share

As Ynau suggested in a comment, in the general case, it would be better to save everything on the stack instead of the heap (using new creates a line on the heap), therefore (assuming UTF8 encoding):

 NSString *foo = @"Foo"; std::string bar([foo UTF8String]); 
+48
Feb 18 '14 at 13:52
source share

As noted in philjordan.eu , it could also be that NSString is zero. In this case, the throw should be performed as follows:

// NOTE: if foo is nil, this will result in an empty C ++ line

// instead of dereferencing the NULL pointer from UTF8String.

This will lead you to such a conversion:

 NSString *foo = @"Foo"; std::string bar = std::string([foo UTF8String], [foo lengthOfBytesUsingEncoding:NSUTF8StringEncoding]); 
+1
May 24 '17 at 9:12 a.m.
source share



All Articles