iPhone:编码问题
我正在打开一个包含语言数据的文本文件并将其读入字典。该代码检索所有数据,但我无法获得正确的编码。文本文件中的字符(例如“”)被翻译为“√Ç”而不是“å”。
我开始对这个问题感到非常恼火,如果有人可以帮助我,我真的很感激......
代码:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *path = [[NSBundle mainBundle] pathForResource:[defaults objectForKey:@"language"]
ofType:@"properties"];
NSMutableDictionary *languageDictionary = [[NSMutableDictionary alloc] init];
char character[1024];
FILE *languageData = fopen([path cStringUsingEncoding:NSISOLatin1StringEncoding], "r");
if (languageData == NULL) NSLog([path stringByAppendingString:@" not found"]);
else
{
//check if end of line flag is set, and end while if so
while (!feof(languageData))
{
fgets(character, 1024, languageData);
NSString *stringFromChar = [NSString stringWithCString:character length:strlen(character)];
NSArray *stringFromCharArray = [stringFromChar componentsSeparatedByString:@" = "];
if(2 == [stringFromCharArray count])
{
[languageDictionary setObject:[stringFromCharArray objectAtIndex:1] forKey:[stringFromCharArray objectAtIndex:0]];
}
}
fclose(languageData);
}
I am opening a text file containing language data and reading it into a dictionary. The code retrieves all the data, but I can`t get the encoding right. Characters in the text file like for instance "Â" gets translated to "√Ç" instead of "å".
I`m starting to get really annoyed by this problem, and i really appreciate if someone can help me out...
CODE:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *path = [[NSBundle mainBundle] pathForResource:[defaults objectForKey:@"language"]
ofType:@"properties"];
NSMutableDictionary *languageDictionary = [[NSMutableDictionary alloc] init];
char character[1024];
FILE *languageData = fopen([path cStringUsingEncoding:NSISOLatin1StringEncoding], "r");
if (languageData == NULL) NSLog([path stringByAppendingString:@" not found"]);
else
{
//check if end of line flag is set, and end while if so
while (!feof(languageData))
{
fgets(character, 1024, languageData);
NSString *stringFromChar = [NSString stringWithCString:character length:strlen(character)];
NSArray *stringFromCharArray = [stringFromChar componentsSeparatedByString:@" = "];
if(2 == [stringFromCharArray count])
{
[languageDictionary setObject:[stringFromCharArray objectAtIndex:1] forKey:[stringFromCharArray objectAtIndex:0]];
}
}
fclose(languageData);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你不应该这样做吗:
否则你将把你的字符串加载为8位字符......
Shouldn't you be doing:
Otherwise you are loading up your strings as 8 bit chars...
找出文件的编码是什么(XCode:cmd+i,您选择的文本编辑器:另存为),然后尝试使用描述的适当的 NSString 方法/编码 此处。
Find out what the encoding of the file is (XCode: cmd+i, Texteditor of your choice: Save As) then try with appropriate NSString method/encoding described here.