在一个字符串中计算“$”出现的次数(Objective C)

4
我想知道在Objective-C语言中,是否有一种简单的方法来查找字符串中特定字符(如“$”)出现的次数。
我使用的真实世界例子是一个类似于下面的字符串:
542$764$231$DataEntry

我需要做的第一件事是:
1)计算“$”出现的次数,以了解DataEntry在我的数据库中处于什么层级(我的数据库结构是我自己设计的)
2)然后我需要获取所有数字,因为它们是索引号。这些数字需要存储在一个NSArray中。我将循环遍历它们,获取不同的索引号。我不会解释我的数据库结构如何工作,因为那不相关。
基本上,从NSString中,我需要知道“$”出现的次数,以及在美元符号之间的所有数字。在PHP中完成这个任务很容易,但我想知道如何在Objective-C中完成这个任务。
谢谢,
迈克尔
3个回答

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

有什么想法可以让我获取$符号之间的数字吗? - Michael King
1
只需省略计数调用即可:NSArray *components = [str componentsSeparatedByString:@"$"]; - J Shapiro
从组件数组中删除第一个和最后一个对象。 - Parag Bafna

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 可能是首选方法,对于模式具有简单重复分隔符的情况下,其性能更佳;但出于完整性考虑,我包括了这种方法。


谢谢你的正则表达式方法!非常有用的信息!如果事情变得复杂,我一定会记在心里! - Michael King

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接