如何将NSString转换为std :: string? [英] How do I convert a NSString into a std::string?
问题描述
我有一个NSString
对象,想将其转换为std::string
.
如何在Objective-C ++中做到这一点?
NSString *foo = @"Foo";
std::string bar = std::string([foo UTF8String]);
几年后,让我扩展这个答案.正确地指出,如果最终要使用std::string
,则很可能希望将cStringUsingEncoding:
与NSASCIIStringEncoding
一起使用.您可以将UTF-8与普通的std::strings
一起使用,但请记住,这些操作针对字节而不是字符甚至字形.为了获得良好的入门",请查看此问题及其答案. >
还请注意,如果您有一个无法用ASCII表示的字符串,但仍希望在std::string
中使用它,并且您不希望在其中使用非ASCII字符,则可以使用dataUsingEncoding:allowLossyConversion:
来获取包含有损ASCII内容的字符串的NSData
表示形式,然后将其扔到您的std::string
I have an NSString
object and want to convert it into a std::string
.
How do I do this in 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
这篇关于如何将NSString转换为std :: string?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!