如何格式化使用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

尽管,我尝试修剪空白但还是没有运气!

谢谢

解决方法

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

基于此,我仍然怀疑字符串后面有一些有趣的东西,并提供了在代码中修复它的方法。

        // Note C strlen will stop at the first 0
        char     * s            = "3Lm9dGmeTf3Lm9dGmeTf3Lm9dGmeTfdd\0\0\0";
        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:@"%@%@",keyFormatted );