如何格式化使用 NSASCIIStringEncoding 编码的字符串

How to format string encoded with NSASCIIStringEncoding

在我的 Objective-C 项目中,我正在从 cloudKit 中获取一个密钥,并想像这样格式化它,想知道格式化有什么问题,

    [cloudKitDB performQuery:query inZoneWithID:nil completionHandler:^(NSArray<CKRecord *> * _Nullable results, NSError * _Nullable error) {

    NSString *key = [[NSString alloc] initWithData:[results.firstObject objectForKey:@"keyvalue"] encoding:NSASCIIStringEncoding];
    NSLog(@"First Key Output: %@",key);
    NSLog(@"Second Key Output: %@",key);

    NSString *formattedKey = [NSString stringWithFormat:@"%@%@",[key stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]], @"1234"];
    NSLog(@"Formatted Key: %@",formattedKey);

这里是我的记录

2020-08-15 21:08:14.704650+0700 myapp[2208:79554] First Key Output: ADEvXp2F2BFJ2E4Lm2dSnYvHENhkFrK8
2020-08-15 21:08:14.704828+0700 myapp[2208:79554] Second Key Output: ADEvXp2F2BFJ2E4Lm2dSnYvHENhkFrK8
2020-08-15 21:08:14.705456+0700 myapp[2208:79554] Formatted Key: ADEvXp2F2BFJ2E4Lm2dSnYvHENhkFrK8

虽然,我已经尝试 trim 空白,但仍然没有成功!

谢谢

这是一个奇怪的问题,但我可以用下面的代码重现它。

基于此,我仍然怀疑字符串背后有一些有趣的地方,并给出了在代码中修复它的方法。

        // Note C strlen will stop at the first 0
        char     * s            = "3Lm9dGmeTf3Lm9dGmeTf3Lm9dGmeTfdd[=10=][=10=][=10=]";
        NSData   * data         = [NSData dataWithBytes:s length:strlen( s ) + 2];
        NSString * key          = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
        NSString * keyFormatted = [NSString stringWithFormat:@"%@%@", key, @"1234"];

        NSLog ( @"Key          : %@", key );
        NSLog ( @"Formatted key: %@", keyFormatted );

        // Use strlen to get rid of funnies
        NSData   * dataFixed = [data subdataWithRange:NSMakeRange( 0, strlen( s ) )];
        NSString * keyFixed  = [[NSString alloc] initWithData:dataFixed encoding:NSASCIIStringEncoding];
        NSString * keyForm2  = [NSString stringWithFormat:@"%@%@", keyFixed, @"1234"];

        NSLog ( @"Fixed key    : %@", keyFixed );
        NSLog ( @"Formatted key: %@", keyForm2 );

        // Use C isprint to trim ... crude but works
        while ( key.length && ! isprint ( [key characterAtIndex:key.length - 1] ) )
        {
            key = [key substringToIndex:key.length - 1];
        }

        keyFormatted = [NSString stringWithFormat:@"%@%@", key, @"1234"];

        NSLog ( @"Key          : %@", key );
        NSLog ( @"Formatted key: %@", keyFormatted );