2010-03-22 62 views
2

之间的字符串我有此内容的字符串:搜索两个已知的字符串

href="http://www.website.com/" /> [...] [...] 

我只想得到字符串的核心部分。如何获得@“href =”“和@”“/>”

之间的部分注意:即使它看起来像xml代码,它也是在NSString中。

回答

10

我明白了!

这是代码(不是很好写的):

NSRange rr2 = [content rangeOfString:@"href=\""]; 
    NSRange rr3 = [content rangeOfString:@"\" />"]; 
    int lengt = rr3.location - rr2.location - rr2.length; 
    int location = rr2.location + rr2.length; 
    NSRange aa; 
    aa.location = location; 
    aa.length = lengt; 
    theString = [theString substringWithRange:aa]; 
+0

写起来真的不是很好,但对我来说这非常有用;) – doxsi 2014-02-06 18:23:41

2

如何

NSString* newNSString =[[[theString substringFromIndex:6] componentsSeparatedByString:@"/\""]objectAtIndex:0]; 

或者

NSString* newNSString =[[[[theString componentsSeparatedByString:@"href=\""]objectAtIndex:1] componentsSeparatedByString:@"/\""]objectAtIndex:0]; 
+0

值得注意的是,创建这些临时字符串组件的效率相当低效。 – 2012-04-12 17:28:13

1

这可以更紧凑地进行:

NSRange end = [source rangeOfString:@"\" />"]; 
if (end.location != NSNotFound) { 
    result = [source substringWithRange:NSMakeRange(6, end.location - 6)]; 
}