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

后端 未结 3 889
别跟我提以往
别跟我提以往 2020-12-07 20:03

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

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

3条回答
  •  感动是毒
    2020-12-07 20:25

    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

提交回复
热议问题