[英]NSString to char* with greek characters
我正在使用以下代码将字符串数据存储在char *中。
NSString *hotelName = [components[2] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
hotelInfo->hotelName = malloc(sizeof(char) * hotelName.length + 1);
strncpy(hotelInfo->hotelName, [hotelName UTF8String], hotelName.length + 1);
NSLog(@"HOTEL NAME: %s",hotelInfo->hotelName);
问题在于打印出奇怪的希腊字符。 我也尝试使用其他编码(例如NSWindowsCP1253StringEncoding -it crashes-)
我什至尝试:
hotelInfo->hotelName = (const char *)[hotelName cStringUsingEncoding:NSUnicodeStringEncoding];
但它也会产生奇怪的字符。
我想念什么?
编辑:经过一些建议,我尝试了以下操作:
if ([hotelName canBeConvertedToEncoding:NSWindowsCP1253StringEncoding]){
const char *cHotelName = (const char *)[hotelName cStringUsingEncoding:NSWindowsCP1253StringEncoding];
int bufSize = strlen(cHotelName) + 1;
if (bufSize >0 ){
hotelInfo->hotelName = malloc(sizeof(char) * bufSize);
strncpy(hotelInfo->hotelName, [hotelName UTF8String], bufSize);
NSLog(@"HOTEL NAME: %s",hotelInfo->hotelName);
}
}else{
NSLog(@"String cannot be encoded! Sorry! %@",hotelName);
for (NSInteger charIdx=0; charIdx<hotelName.length; charIdx++){
// Do something with character at index charIdx, for example:
char x[hotelName.length];
NSLog(@"%C", [hotelName characterAtIndex:charIdx]);
x[charIdx] = [hotelName characterAtIndex:charIdx];
NSLog(@"%s", x);
if (charIdx == hotelName.length - 1)
hotelInfo->hotelName = x;
}
NSLog(@"HOTEL NAME: %s",hotelInfo->hotelName);
}
但是还是没有!
首先,不能保证任何NSString
都可以表示为C字符数组(所谓的C-String )。 原因是只能使用有限的字符集。 您应该检查字符串是否可以转换(通过调用canBeConvertedToEncoding:
。
其次,当使用malloc
和strncpy
函数时,它们依赖于C-String的长度,而不是NSString
的长度。 因此,您应该首先从NSString获取C-String,然后获取其长度( strlen
),并将此值用于函数调用:
const char *cHotelName = (const char *)[hotelName cStringUsingEncoding:NSWindowsCP1253StringEncoding];
int bufSize = strlen(cHotelName) + 1;
hotelInfo->hotelName = malloc(sizeof(char) * bufSize);
strncpy(hotelInfo->hotelName, cHotelName, bufSize);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.