2010-03-22 4 views
2

J'ai une chaîne avec ce contenu:Rechercher une chaîne entre deux chaînes connues

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

Je veux juste obtenir la partie centrale de la chaîne. Comment est-il possible d'obtenir la partie entre @ "href =" "et @" "/>"

Remarque: Même s'il ressemble à du code XML, il est à l'intérieur d'un NSString.

Répondre

10

Je l'ai eu!

C'est le code (pas très bien écrit):

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

Ce n'est vraiment pas très joli écrit, mais c'était utile pour moi;) – doxsi

2

Que diriez-vous

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

Ou

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

Il est à noter qu'il est assez inefficace de créer ce tableau temporaire de composants de chaîne. –

1

Cela peut se faire de manière plus compacte:

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