-[__NSCFString deleteCharactersI

2018-09-12  本文已影响0人  Sunday_David

写在前面

场景

错误做法

    NSString *str = @"今天我们来学习NSCharacterSet我们快乐";
    NSString *str1 = @"我sS今";
    
    NSMutableString *resultStr = [NSMutableString stringWithString:str];
    
    for (int i = 0; i < str.length; i++) {
        NSRange indexRange = NSMakeRange(i, 1);
        NSString *indexStr = [str substringWithRange:indexRange];
        if ([str1 containsString:indexStr]) {
            
            if (indexRange.location != NSNotFound) {
                NSLog(@"str.length = %lu",str.length);
                NSLog(@"resultStr.length = %lu",resultStr.length);
                NSLog(@"indexRange = %@",NSStringFromRange(indexRange));
                [resultStr deleteCharactersInRange:indexRange];
            }
        }
    }

报错

2018-09-12 03:46:23.686670+0800 NSCharacterSet[2414:36081] *** Terminating app due to uncaught exception 'NSRangeException', reason: '-[__NSCFString deleteCharactersInRange:]: Range or index out of bounds'
         *** First throw call stack:
         (
         0   CoreFoundation                      0x00007fff471482db __exceptionPreprocess + 171
         1   libobjc.A.dylib                     0x00007fff6e2e9c76 objc_exception_throw + 48
         2   CoreFoundation                      0x00007fff471d9d7d +[NSException raise:format:] + 205
         3   CoreFoundation                      0x00007fff47187945 mutateError + 261
         4   NSCharacterSet                      0x0000000100000ded main + 445
         5   libdyld.dylib                       0x00007fff6ef03015 start + 1
         6   ???                                 0x0000000000000001 0x0 + 1
         )
         libc++abi.dylib: terminating with uncaught exception of type NSException
         (lldb)

原因分析

解决方法

方法一

        for (int i = 0; i < resultStr.length; i++) {
// 方法一,用变化(可变字符串)的字符串(resultStr)的长度

方法二(推荐)

for (int i = (int)str.length - 1 ; i >= 0; i--) {
// 方法二,使用原来的字符串(str.length)。 (强制转换(int),可去除警告⚠️:Implicit conversion loses integer precision: 'unsigned long' to 'int')

方法三

    NSString *str = @"今天我们来学习NSCharacterSet我们快乐";
    NSString *str1 = @"我sS今";
    
    NSMutableString *resultStr = [NSMutableString string];
    
   for (int i = 0; i < str.length; i++) {
   
        NSRange indexRange = NSMakeRange(i, 1);
        NSString *indexStr = [str substringWithRange:indexRange];
        
        if (![str1 containsString:indexStr]) { 
             // 方法三,创建一个新的可变字符串,删除操作改为添加操作 
            [resultStr appendString:indexStr];
        }
    }

方法四

    NSString *str2 = @"今天我们来学习NSCharacterSet我们快乐";
    NSCharacterSet *characterSet = [NSCharacterSet characterSetWithCharactersInString:@"我sS今"];
    NSArray *setArray = [str2 componentsSeparatedByCharactersInSet:characterSet];
    NSLog(@"setArray = %@", setArray);
    NSString *resultStr2 = [setArray componentsJoinedByString:@""];
    NSLog(@"resultStr2 = %@", resultStr2);

方法五

方法N

上一篇 下一篇

猜你喜欢

热点阅读