提取字符串的一部分

时间:2014-02-14 08:05:27

标签: ios objective-c nsstring

我有很多字符串看起来像这样:

Soccer Livescore: (POR-SF) #Rio Ave vs #SC Braga: 2-1
Soccer Livescore: (ENG-FC) #Chester FC vs #Halifax: 1-0

如何在 - ?

的每一侧的()和整数之间提取字符串

3 个答案:

答案 0 :(得分:0)

可能你想看看NSString标记化:NSString tokenize in Objective-C 其中一个答案中有样本:

NSString *string = @"oop:ack:bork:greeble:ponies";
NSArray *chunks = [string componentsSeparatedByString: @":"];

答案 1 :(得分:0)

请参阅NSString的以下方法:

rangeOfString:(用它来寻找'('和')') substringWithRange:(获取子串'TM1-TM2') componentsSeparatedByString:(用' - '字符分割字符串)。

答案 2 :(得分:0)

这是答案。

NSString *string =@"Soccer Livescore: (CONMEBOL-GS) #Rio Ave vs #SC Braga: 2-1";

NSRange range1 = [string rangeOfString:@"("];
NSRange range2 = [string rangeOfString:@")"];
range1.location = range1.location + 1;
range1.length = range2.location - range1.location;


NSString *scoreString = [string substringWithRange:NSMakeRange([string length]-3, 3)];
NSArray *scores = [scoreString componentsSeparatedByString:@"-"];

NSLog(@"%@ %d %d", [string substringWithRange:range1], [scores[0] intValue], [scores[1] intValue]);

日志结果:CONMEBOL-GS 2 1