How to covert std::string to NSString?Look at the last picture

349 views Asked by At

How to covert std::string to NSString? ,why the result is garbled?I use lldb command po ,look at the console ,the red arrow,the _data display correct string?Why?

 std::string resultString = getResult();
 NSString *str= [NSString stringWithCString:resultString.c_str() encoding:NSUTF8StringEncoding];

but the str is garbled,like enter image description here

enter image description here

why str's value = nil

enter image description here

enter image description here

1

There are 1 answers

8
Mehul Patel On BEST ANSWER

May be here issue is with string encoding. I have done little test on this input string and found some result on that.

Here I have use complex string "\x18\xa4\tp\x01" which you shown in your log. From the result I conclude that NSUTF8StringEncoding encoding string is not working with above string.

Here is code:

+ (void) stringTest {

    std::string *resultString = new std::string("\x18\xa4\tp\x01");

    NSString *str= [NSString stringWithCString:resultString->c_str() encoding:NSUTF8StringEncoding];
    NSString *str2= [NSString stringWithCString:resultString->c_str() encoding:NSASCIIStringEncoding];
    NSString *str3= [NSString stringWithCString:resultString->c_str() encoding:[NSString defaultCStringEncoding]];

    NSLog(@"str :%@",str);
    NSLog(@"str2 :%@",str2);
    NSLog(@"str3 :%@",str3);
}

And a reference image for log:

enter image description here

Here you can see that NSUTF8StringEncoding returns nil string and other encoding gives a result. I'm not sure which encoding scheme is valid for your string. If we know that encoding scheme for resultString string then we can get more accurate result here.