How to convert std::string to NSString?

Objective CNsstringObjective C++Stdstring

Objective C Problem Overview


Hi I am trying to convert a standard std::string into an NSString but I'm not having much luck.

I can convert successfully from an NSString to a std::string with the following code

NSString *realm = @"Hollywood";
std::string REALM = [realm cStringUsingEncoding:[NSString defaultCStringEncoding]];

However I get a compile time error when I try the following

NSString *errorMessage = [NSString stringWithCString:REALM encoding:[NSString defaultCStringEncoding]];

The error I get is

Cannot convert 'std::string' to 'const char*' in argument passing

Am I missing something here?

Thanks in advance.

Objective C Solutions


Solution 1 - Objective C

Get c-string out of std::string for conversion:

NSString *errorMessage = [NSString stringWithCString:REALM.c_str() 
                                   encoding:[NSString defaultCStringEncoding]];

Solution 2 - Objective C

Firstly, you've got to be using Objective-C++ for this to work in the slightest; easiest way to ensure that is rename all your *.m files to *.mm

By far the most usable (non-deprecated) manual way of getting a C++ std::string into an NSString is with:

std::string param; // <-- input
NSString* result = [NSString stringWithUTF8String:param.c_str()];
NSString* alternative = [[NSString alloc] initWithUTF8String:param.c_str()];

This will work in most cases - and if you're not doing specific encoding detection and conversion, UTF-8 is going to give you a good result for having non-latin characters 'just work.'

If you're making a bigger app, or you're not the only one working on it, however - you'll probably want something that's easier to apply.

Adapted from cocoa-dev mailing list archives

@interface NSString (cppstring_additions)
+(NSString*) stringWithwstring:(const std::wstring&)string;
+(NSString*) stringWithstring:(const std::string&)string;
-(std::wstring) getwstring;
-(std::string) getstring;
@end

@implementation NSString (cppstring_additions)

#if TARGET_RT_BIG_ENDIAN
const NSStringEncoding kEncoding_wchar_t = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingUTF32BE);
#else
const NSStringEncoding kEncoding_wchar_t = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingUTF32LE);
#endif

+(NSString*) stringWithwstring:(const std::wstring&)ws
{
	char* data = (char*)ws.data();
	unsigned size = ws.size() * sizeof(wchar_t);
	
	NSString* result = [[NSString alloc] initWithBytes:data length:size encoding:kEncoding_wchar_t];
	return result;
}
+(NSString*) stringWithstring:(const std::string&)s
{
	NSString* result = [[NSString alloc] initWithUTF8String:s.c_str()];
	return result;
}

-(std::wstring) getwstring
{
	NSData* asData = [self dataUsingEncoding:kEncoding_wchar_t];
	return std::wstring((wchar_t*)[asData bytes], [asData length] / sizeof(wchar_t));
}
-(std::string) getstring
{
	return [self UTF8String];
}

@end

With that in-place (and appropriately #imported) you can now:

NSString* result = [NSString stringWithstring:param];
string convertedBack = [result getstring];

And the same for std::wstring, which is more than handy.

Solution 3 - Objective C

NSString* mystring = [NSString stringWithUTF8String:stdstring.c_str()];

Solution 4 - Objective C

Apple now has a new way they want you to do this conversion. In XCode7, I used the Edit > Convert > To Modern Objective C Syntax... option to find this out. It uses a shorthand @ symbol.

std::string sCPPString = "Hello World!";
NSString *sAppleString = @(sCPPString.c_str());

Solution 5 - Objective C

I've also found that:

NSString *nsString = [NSString stringWithFormat:@"%s",standardString];

Works like a champ.

Solution 6 - Objective C

Here is the code snippet/example:

string str_simple = "HELLO WORLD";

//string to NSString
NSString *stringinObjC = [NSString stringWithCString:str_simple.c_str()
								encoding:[NSString defaultCStringEncoding]];			
NSLog(stringinObjC);


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
QuestionAnthony McCormickView Question on Stackoverflow
Solution 1 - Objective CVladimirView Answer on Stackoverflow
Solution 2 - Objective CrvalueView Answer on Stackoverflow
Solution 3 - Objective CJohn BowersView Answer on Stackoverflow
Solution 4 - Objective CVolomikeView Answer on Stackoverflow
Solution 5 - Objective CBadPirateView Answer on Stackoverflow
Solution 6 - Objective CDeepak KumarView Answer on Stackoverflow