简体   繁体   English

如何将NSString转换为std :: string?

[英]How do I convert a NSString into a std::string?

I have an NSString object and want to convert it into a std::string . 我有一个NSString对象,并希望将其转换为std::string

How do I do this in Objective-C++? 我如何在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 . 正如所指出的那样,如果你最终要使用std::string ,你最有可能想要使用cStringUsingEncoding:使用NSASCIIStringEncoding 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. 您可以将UTF-8与普通的std::strings ,但请记住,这些操作是基于字节而不是字符甚至是字形。 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 另请注意,如果您的字符串不能表示为ASCII但仍然需要它在std::string并且您不希望其中包含非ASCII字符,则可以使用dataUsingEncoding:allowLossyConversion:获取具有有损编码的ASCII内容的字符串的NSData表示,然后将其抛出到std::string

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): 正如Ynau在评论中所建议的那样,在一般情况下,最好将所有内容保存在堆栈而不是堆中(使用new在堆上创建字符串),因此(假设UTF8编码):

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

As noted on philjordan.eu it could also be that the NSString is nil . philjordan.eu所述 ,也可能是NSString nil In such a case the cast should be done like this: 在这种情况下,演员应该这样做:

// NOTE: if foo is nil this will produce an empty C++ string //注意:如果foo为nil,这将产生一个空的C ++字符串

// instead of dereferencing the NULL pointer from UTF8String. //而不是从UTF8String中取消引用NULL指针。

This would lead you to such a conversion: 这将导致您进行这样的转换:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM