将带有重音字符的 NSString 转换为 CString
我有一个 NSString,其值为 Jose(e 上有重音符号)。我尝试将其转换为 C 字符串,如下所示:
char str [[myAccentStr length] + 1];
[myAccentStr getCString:str maxLength:[myAccentStr length] + 1 encoding:NSUTF32StringEncoding];
但 str 最终成为空字符串。什么给?我也尝试过UTF8和UTF16。它稍后会传递给另一个函数,当该函数调用 lstrlen 时,大小将为零。
I have an NSString with a value of Jose (an accent on the e). I try to convert it to a C string as follows:
char str [[myAccentStr length] + 1];
[myAccentStr getCString:str maxLength:[myAccentStr length] + 1 encoding:NSUTF32StringEncoding];
but str ends up being an empty string. What gives? I tried UTF8 and UTF16 too. It gets passed to another function later on and when that funcsion calls lstrlen on it, the size comes out as zero.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
NSString getCString:maxLength:encoding 说:
使用 NSString 方法 dataUsingEncoding:allowLossyConversion: 就可以了。这是一个代码示例:
NSLog 的输出是:
到目前为止,我只在使用 NSMacOSRomanStringEncoding 时看到它正常工作。
编辑
将其更改为社区 wiki。请随意编辑。
hooleyhoop 有一些很棒的观点,所以我想我会尝试编写尽可能详细的代码。如果我遗漏了任何内容,请有人插话。
另外 - 不知道为什么 [NSString canBeConvertedToEncoding:] 返回 YES,即使 [NSString getCString:maxLength:encoding:] 函数肯定无法正常工作(如输出所示) )。
以下是一些代码,可帮助分析哪些有效/哪些无效:
结果:
The docs for NSString getCString:maxLength:encoding says:
Using the NSString method dataUsingEncoding:allowLossyConversion: does the trick. Here's a code example:
The output from that NSLog is:
So far I've only seen this work properly when using the NSMacOSRomanStringEncoding.
Edit
Changing this to a community wiki. Please feel free to edit.
hooleyhoop had some great points, so I thought I would try to make code that is as verbose as possible. If I'm missing anything, someone please chime in.
Also - Not sure why [NSString canBeConvertedToEncoding:] is returning YES even though the [NSString getCString:maxLength:encoding:] function definitely isn't working right (as seen by the output).
Here's some code to help in analyzing what works / what doesn't:
Results:
[aString length]
返回字符数。在您的情况下,这是4。您可以使用例如 NSUTF8StringEncoding、NSUTF16StringEncoding、NSUTF32StringEncoding 准确地将字符串转换为 ac 字符串。长度以字节为单位分别为5、8、16。
出于转换目的,您应该使用
-maximumLengthOfBytesUsingEncoding
而不是-lengthOfBytesUsingEncoding
始终使用
-canBeConvertedToEncoding
检查转换是否有效使用 NSString 有充分的理由
[aString length]
returns the number of characters. In your case this is 4.You can convert your string to a c string accurately using, for example, NSUTF8StringEncoding, NSUTF16StringEncoding, NSUTF32StringEncoding. The length in bytes would be 5, 8, 16 respectively.
For conversion purposes you should use
-maximumLengthOfBytesUsingEncoding
instead of-lengthOfBytesUsingEncoding
Always check that the conversion is valid with
-canBeConvertedToEncoding
There are good reasons to use NSString