gpt4 book ai didi

ios - NSString 到带有希腊字符的 char*

转载 作者:行者123 更新时间:2023-11-29 00:29:01 25 4
gpt4 key购买 nike

我使用以下代码将字符串数据存储在 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:)。

其次,当使用mallocstrncpy函数时,它们依赖于C-String的长度,而不是C-String的长度NSString。因此,您应该首先从 NSString 获取 C 字符串,然后获取它的长度 (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);

关于ios - NSString 到带有希腊字符的 char*,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42361800/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com