【问题标题】:Count the amount of times '$' shows up in a string (Objective C)计算“$”在字符串中出现的次数(目标 C)
【发布时间】:2012-11-14 01:54:16
【问题描述】:

我想知道是否有一种简单的方法可以找到诸如“$”之类的字符在 Objective-c 语言的字符串中出现的次数。

我使用的实际示例是一个字符串,如下所示:

542$764$231$DataEntry

我首先要做的是:

1) 计算“$”出现的次数,以了解 DataEntry 在我的数据库中的哪一层(我的数据库结构是我编造的)

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

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

谢谢,

迈克尔

【问题讨论】:

    标签: objective-c arrays string int


    【解决方案1】:
    [[@"542$764$231$DataEntry" componentsSeparatedByString:@"$"] count]-1
    

    【讨论】:

    • 谢谢!关于如何获得 $ 之间的数字的任何想法?
    • 省略计数调用:NSArray *components = [str componentsSeparatedByString:@"$"];
    • 从组件数组中移除第一个和最后一个对象。
    【解决方案2】:

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

    #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 可能是首选方法,并且在模式具有简单重复分隔符的情况下性能更高;但为了完整起见,我包含了这种方法。

    【讨论】:

    • 感谢您的正则表达式方法!这是非常有用的信息!如果事情变得复杂,我一定会记住这一点!
    【解决方案3】:

    试试这个代码:

        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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-02-04
      • 2011-04-21
      • 1970-01-01
      • 2011-05-13
      • 2014-04-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多