计算'$'出现在字符串中的次数(Objective C)

时间:2012-11-26 14:57:39

标签: objective-c arrays string int

我想知道是否有一种简单的方法可以找到字符(例如'$')出现在语言objective-c中的字符串中的次数。

我使用的真实世界示例是一个看起来像的字符串:

542$764$231$DataEntry

首先我需要做的是:

1)计算'$'显示的数量,以了解DataEntry在我的数据库中的等级(我的数据库结构是我编写的)

2)然后我需要获得所有数字,因为它们是索引号。这些数字需要存储在NSArray中。我将遍历它们所有获得不同的索引。我不打算解释我的数据库结构是如何工作的,因为这是不相关的。

基本上从那个NSString,我需要,'$'显示的次数。美元符号之间的所有数字。这在PHP中可以轻而易举,但我很想知道如何在Objective-C中实现这一点。

谢谢,

迈克尔

3 个答案:

答案 0 :(得分:4)

[[@"542$764$231$DataEntry" componentsSeparatedByString:@"$"] count]-1

答案 1 :(得分:1)

@Parag Bafna和@J Shapiro或componentsSeparatedByString建议的NSRegularExpression例如:

#import <Foundation/Foundation.h>

int main(int argc, char *argv[]) {
    @autoreleasepool {
        NSError *error = NULL;
        NSString *searchText = @"542$764$231$DataEntry";
        NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"(\\d{3})\\$" options:NSRegularExpressionCaseInsensitive error:&error];
        NSUInteger numberOfMatches = [regex numberOfMatchesInString:searchText options:0 range:NSMakeRange(0, [searchText length]) ];

        printf("match count = %ld\n",numberOfMatches);
        [regex enumerateMatchesInString:searchText 
                                options:0 
                                  range:NSMakeRange(0,[searchText length]) 
                             usingBlock:^(NSTextCheckingResult *match, NSMatchingFlags flags, BOOL *stop){
            NSRange range = [match rangeAtIndex:1];
            printf("match = %s\n",[[searchText substringWithRange:range] UTF8String]);
        }];     
    }
}

componentsSeparatedByString可能是首选的方法,并且在模式具有简单重复分隔符的情况下性能更高;但为了完整起见,我把这种方法包括在内。

答案 2 :(得分:0)

试试这段代码:

    NSMutableArray* substrings=[NSMutableArray new];
    // This will contain all the substrings
    NSMutableArray* numbers=[NSMutableArray new];
    // This will contain all the numbers
    NSNumberFormatter* formatter=[NSNumberFormatter new];
    // The formatter will scan all the strings and estabilish if they're
    // valid numbers, if so it will produce a NSNumber object
    [formatter setNumberStyle: NSNumberFormatterDecimalStyle];
    NSString* entry= @"542$764$231$DataEntry";
    NSUInteger count=0,last=0;
    // count will contain the number of '$' characters found
    NSRange range=NSMakeRange(0, entry.length);
    // range is the range where to check
    do
    {
        range= [entry rangeOfString: @"$" options: NSLiteralSearch range: range];
        // Check for a substring
        if(range.location!=NSNotFound)
        {
            // If there's not a further substring range.location will be NSNotFound
            NSRange substringRange= NSMakeRange(last, range.location-last);
            // Get the range of the substring
            NSString* substring=[entry substringWithRange: substringRange];
            [substrings addObject: substring];
            // Get the substring and add it to the substrings mutable array
            last=range.location+1;
            range= NSMakeRange(range.location+range.length, entry.length-range.length-range.location);
            // Calculate the new range where to check for the next substring
            count++;
            // Increase the count
        }
    }while( range.location!=NSNotFound);
    // Now count contains the number of '$' characters found, and substrings
    // contains all the substrings separated by '$'
    for(NSString* substring in substrings)
    {
        // Check all the substrings found
        NSNumber* number;
        if([formatter getObjectValue: &number forString: substring range: nil error: nil])
        {
            // If the substring is a valid number, the method returns YES and we go
            // inside this scope, so we can add the number to the numbers array
            [numbers addObject: number];
        }
    }
    // Now numbers contains all the numbers found