将C++字符串转换为NSString

3

我如何将下面的代码转换为 NSString

std::cout << "Cipher Text (" << ciphertext.size() << " bytes)" << std::endl;

for( int i = 0; i < ciphertext.size(); i++ ) {

    std::cout << "0x" << std::hex << (0xFF & static_cast<byte>(ciphertext[i])) << " ";
}

std::cout << std::endl << std::endl;

我尝试过:
 NSString *cyp = [NSString stringWithUTF8String:ciphertext.c_str()];

但是NSString为空。
NSString *cyp = @(ciphertext.c_str());
NSLog(@"cypher %@",cyp);
NSLog(@"cypher %s",ciphertext.c_str());

打印输出:

Pas[8044:70b] playntext Now is the time for all good men to come to the aide...
2013-11-27 14:38:01.421 Pas[8044:70b] cypher (null)
2013-11-27 14:38:01.422 Pas[8044:70b] cypher ¯≥Íä≥z=(fúóß≥¢P%Ä’“2ŒË
W3ÔpˇHÈËò©¬^ß∞@C°¸#±°Î≤ˆóbp°Å nxÄê
2013-11-27 14:38:01.423 Pas[8044:70b] decrypted Now is the time for all good men to come to the aide...

那么为什么我可以将它打印出来像一个字符串,但无法从“ciphertext”创建一个NSString呢?

NSString stringWithCString:encoding: 使用不同的编码方式。 同时请检查 ciphertext.c_str() 的返回值 :) - Dobroćudni Tapir
几乎可以确定该字符串未以UTF8编码 - Hot Licks
或者(在更仔细的检查中似乎是这种情况),它确实是密文,那么它不是真正的“字符串”--它不是字符数据。 - Hot Licks
要打印密文,您应该以十六进制(另一个问题)或Base64格式进行打印。 - Hot Licks
1个回答

3

我尝试这个方法,它对我有效:

NSString *s1 = @(YOURCSTRING.c_str());

对于这个答案,你必须祈祷你的C字符串使用UTF-8。如果是的话,这就是最好的答案。 - JeremyP
如果 YOURCSTRING 类似于 \xffffff80\x02-addListener,即包含非 UTF-8 字符,则 s1 将为 nil - RY_ Zheng

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接