reading unicode from sqlite and creating a NSString

前端 未结 2 700
再見小時候
再見小時候 2021-01-17 05:14

Im working on an iOS app where I need to store and retrieve from an SQLite DB, a representation of a NSString that has subscripts. I can create a NSString at compile time wi

相关标签:
2条回答
  • 2021-01-17 05:36

    I solved the problem like this - error checking removed for clarity -

    the unicode string comes into the parameter stringEncoded from the db like:

    "MgBr\u2082_CH\u2082Cl\u2082"

    +(NSString *)decodeUnicodeBytes:(char *)stringEncoded {
      unsigned int    unicodeValue;
      char            *p, buff[5];
      NSMutableString *theString;
      NSString        *hexString;
      NSScanner       *pScanner;
    
      theString = [[[NSMutableString alloc] init] autorelease];
      p = stringEncoded;
    
      buff[4] = 0x00;
      while (*p != 0x00) {
    
        if (*p == '\\') {
          p++;
          if (*p == 'u') {
            memmove(buff, ++p, 4);
    
            hexString = [NSString stringWithUTF8String:buff];
            pScanner = [NSScanner scannerWithString: hexString];
            [pScanner scanHexInt: &unicodeValue];
    
            [theString appendFormat:@"%C", unicodeValue];
            p += 4;
            continue;
            }
          }
    
        [theString appendFormat:@"%c", *p];
        p++;
        }
    
      return [NSString stringWithString:theString];
    }
    
    0 讨论(0)
  • 2021-01-17 05:44

    You need one of the NSString stringWithCString class methods or the corresponding initWithCString instance methods.

    0 讨论(0)
提交回复
热议问题