【问题标题】:How to convert from NSString to const char* with umlauts in Objective-C?如何在 Objective-C 中使用变音符号从 NSString 转换为 const char*?
【发布时间】:2011-06-17 11:06:10
【问题描述】:

我在将 NSString 中的变音符号转换为 const char* 时遇到问题。

此方法解析单词的文本文件(逐行),将单词保存为 NSArray *results 中的字符串。然后转换为 const char tmpConstChars。例如,此 const char 保存一个 'ä',如 '√§'。如何从 NSString 转换为 const char * - 我认为这是正确的。

- (void)inputWordsByFile:(NSString *)path
{

    NSError *error = [[NSError alloc] init];
    NSString *content = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:&error];
    NSArray *results = [content componentsSeparatedByString:@"\n"];

    NSMutableArray *words = [[NSMutableArray alloc] initWithArray:results];
    [words removeLastObject];
    for(int i=0; i<[words count]; i++){

    const char *tmpConstChars = [[words objectAtIndex:i] UTF8String];
    [self addWordToTree:tmpConstChars];

    }
}

【问题讨论】:

  • 不需要alloc/init error 对象。
  • 问题可能与您查看文本的方式有关...您确定您查看的是 UTF8 感知文本,还是配置为解释 UTF8 编码文本的文本?
  • Xcode 控制台是 UTF8 解释器吗?
  • NSLog(@"%s",tmpConstChars+2);会给我“zählen”的“§hlen”,它应该给我“hlen”。
  • 什么是 NSLog(@"%s",tmpConstChars);给?

标签: objective-c unicode utf-8 character-encoding nsstring


【解决方案1】:

除非我弄错了,UTF8String 方法返回字符串的 UTF-8 编码字节。对于zählen,这些是:

$ perl -MEncode -Mutf8 -E 'say join ", ", map ord, split //, encode("utf8", "zählen")'
122, 195, 164, 104, 108, 101, 110

…其中 是 UTF-8 encoding sequence for ä。因此,当你戳到tmpChars+2 时,你会得到 ASCII 码为 164 的字符。这可能不是你想要的。 unichars 之后你不是更多吗?有一个 characterAtIndex: 方法会返回这些,尽管是一个接一个:

NSString *test = @"zählen";
unichar c = [test characterAtIndex:1];
NSLog(@"---> %C", c); // ---> ä

【讨论】:

  • unichar tmpConstChars = [[words objectAtIndex:i] characterAtIndex:0];
  • 你一定是做错了什么,它对我有用。我将使用示例代码更新答案。
  • @malteriechmann,你用 tmpConstChars 做什么来得到你错误的字符?请记住,unichar 的长度为 2 字节,因此您无法读取 tmpConstChars[2] 并得到 ä。 %C 是 unichar 的正确格式代码。如果您期望 ä 为 224,那么您需要使用 NSISOLatin1StringEncoding 进行解码。但是您将被限制在 Latin1 代码页。
猜你喜欢
  • 2012-02-24
  • 2023-03-11
  • 2012-01-08
  • 2011-07-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多