美文网首页
获取字符串中数字字符串和其所在的位置

获取字符串中数字字符串和其所在的位置

作者: HHLM | 来源:发表于2016-12-07 15:33 被阅读65次
    //找到数字在字符串中得位置
     [[self numberArray] enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            NSString *tmpStr = @"现在开始拍车了!今日总共拍品1200辆,有您的心愿车56辆,赶紧去看看";;
            NSRange range = [tmpStr rangeOfString:obj];
            if (range.location != NSNotFound)
            {
                NSLog(@"found at location = %lu, length = %lu",(unsigned long)range.location,(unsigned long)range.length);
                NSLog(@"%@",obj);
            }
            else
            {
                NSLog(@"Not Found");
            }
        }];
    
    //获取字符串中所有数字字符串
    -(NSMutableArray *)numberArray
    {
        NSString *originalString = @"现在开始拍车了!今日总共拍品1200辆,有您的心愿车56辆,赶紧去看看";;
        
        
        NSMutableArray  *array = [NSMutableArray array];
    
        NSString *tempStr;
        
        NSScanner *scanner = [NSScanner scannerWithString:originalString];
        
        NSCharacterSet *numbers = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
        
        while (![scanner isAtEnd])
        {
            [scanner scanUpToCharactersFromSet:numbers intoString:NULL];
            
            [scanner scanCharactersFromSet:numbers intoString:&tempStr];
            
            if (tempStr&& tempStr.length > 0)
            {
                [array addObject:tempStr];
            }
            tempStr = @"";
        }
        return array;
    }
    
    

    生成32位随机由字母和数字组成的字符串

    //生成32位随机由字母和数字组成的字符串
    - (NSString *)creat32randomString
    {
        char data[32];
        
        for (int i=0; i < 32; i ++)
        {
            char c = (char)('A' + (arc4random_uniform(26)));
            char b = (char)('a' + (arc4random_uniform(26)));
            char a = (char)('0' + (arc4random_uniform(10)));
            
            char ch[3] = {c ,b, a};
            
            int index = arc4random() % 3;
            
            data[i] = ch[index];
        }
        return [[NSString alloc] initWithBytes:data
                                        length:32
                                      encoding:NSUTF8StringEncoding];
        
    }
    
    打印结果:
    2016-12-07 15:30:28.365 HHAnimations[26877:618657] found at location = 14, length = 4
    2016-12-07 15:30:28.944 HHAnimations[26877:618657] 1200
    2016-12-07 15:30:33.356 HHAnimations[26877:618657] found at location = 26, length = 2
    2016-12-07 15:30:33.357 HHAnimations[26877:618657] 56
    
    

    相关文章

      网友评论

          本文标题:获取字符串中数字字符串和其所在的位置

          本文链接:https://www.haomeiwen.com/subject/rqodmttx.html