2010-03-22 55 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)]; 
}