how do I get a substring in iOS?

后端 未结 1 709
失恋的感觉
失恋的感觉 2021-01-24 13:12

I have a string that contains some text:

 

ProductImage [height:60]

and I want to extract just the 60 from it? The 60 is jus

1条回答
  •  北恋
    北恋 (楼主)
    2021-01-24 13:29

    You can use an NSScanner, or search using an NSRegularExpression.

    NSScanner* sc = [NSScanner scannerWithString:s];
    int num;
    [sc scanUpToCharactersFromSet:[NSCharacterSet decimalDigitCharacterSet] 
                       intoString:nil];
    [sc scanInt:&num];
    

    Or:

    int num;
    NSError* err = nil;
    NSRegularExpression* r = [NSRegularExpression regularExpressionWithPattern:@"\\d+"
                                                                       options:0 
                                                                         error:&err];
    // error-checking omitted
    for (NSTextCheckingResult* match in [r matchesInString:s 
                                                   options:0 
                                                     range:NSMakeRange(0, [s length])])
        num = [[s substringWithRange: [match range]] intValue];
    

    0 讨论(0)
提交回复
热议问题