我如何在iOS中获得子字符串? [英] how do I get a substring in iOS?

查看:64
本文介绍了我如何在iOS中获得子字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含一些文字的字符串:

I have a string that contains some text:

 <p>ProductImage [height:60]</p>

我想从中提取60? 60只是这里的任意值

and I want to extract just the 60 from it? The 60 is just an arbitrary value here

推荐答案

您可以使用NSScanner,或使用NSRegularExpression进行搜索。

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];

或者:

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];

这篇关于我如何在iOS中获得子字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆