【问题标题】:Convert c++ string to NSString [duplicate]将c ++字符串转换为NSString [重复]
【发布时间】:2013-12-12 22:12:22
【问题描述】:

如何将下面的代码转换为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()];

但是cyp 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...

那么为什么我可以像字符串一样打印出来却不能从“密文”创建一个NSString

【问题讨论】:

  • NSString stringWithCString:encoding: 使用不同的编码。还要检查 ciphertext.c_str() 返回值 :)
  • 几乎可以肯定该字符串不是以 UTF8 编码的
  • 或者(仔细检查后似乎就是这种情况),它确实是密文,在这种情况下它不是真正的“字符串”——它不是字符数据。
  • 要打印密文,您应该以十六进制(一个单独的问题)或 Base64 打印。

标签: c++ ios objective-c


【解决方案1】:

试试这对我有用:

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

【讨论】:

  • 对于这个答案,你必须祈祷你的 C 字符串使用 UTF-8。如果是这样,这是最好的答案。
  • s1 将是 nil 如果 YOURCSTRING 类似于 \xffffff80\x02-addListener,其中包括非 UTF-8 字符
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-22
  • 1970-01-01
  • 1970-01-01
  • 2020-08-27
  • 2015-11-30
  • 1970-01-01
相关资源
最近更新 更多