2011-10-12 27 views
5

我有一个NSString,最初看起来像<a href="http://link.com"> LinkName</a>。我删除了html标签,现在有一个NSString,看起来像由whiteSpace将NSString分隔为两个NSStrings

http://Link.com SiteName 

我怎样才能将二者分开到不同的NSString这么我会

http://Link.com 

SiteName 

我特别要在标签中显示SiteName,只需使用http://Link.com即可在UIWebView中打开,但我无法在它全是一个字符串。任何建议或帮助,不胜感激。

+0

可能重复[Objective-C中的NSString标记化](http://stackoverflow.com/qu estions/259956/nsstring-tokenize-in-objective-c) –

回答

8
NSString *s = @"http://Link.com SiteName"; 
NSArray *a = [s componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]; 
NSLog(@"http: '%@'", [a objectAtIndex:0]); 
NSLog(@"site: '%@'", [a lastObject]); 

的NSLog输出:

http: 'http://Link.com' 
site: 'SiteName' 

奖金,处理站点名称与一个RE嵌入式空间:

NSString *s = @"<a href=\"http://link.com\"> Link Name</a>"; 
NSString *pattern = @"(http://[^\"]+)\">\\s+([^<]+)<"; 

NSRegularExpression *regex = [NSRegularExpression 
           regularExpressionWithPattern:pattern 
           options:NSRegularExpressionCaseInsensitive 
           error:nil]; 

NSTextCheckingResult *textCheckingResult = [regex firstMatchInString:s options:0 range:NSMakeRange(0, s.length)]; 
NSString *http = [s substringWithRange:[textCheckingResult rangeAtIndex:1]]; 
NSString *site = [s substringWithRange:[textCheckingResult rangeAtIndex:2]]; 

NSLog(@"http: '%@'", http); 
NSLog(@"site: '%@'", site); 

的NSLog输出:的

http: 'http://link.com' 
site: 'Link Name' 
+0

是的,你的权利,它适用于一些“siteName”,但一些间隔以及像“网站名称”,所以我遇到了另一个问题......但我可以使用一些肮脏的编码绕过它,如果theres没有其他方式 – FreeAppl3

+1

你使用正则表达式可能会更好。 – zaph

+0

谢谢@CocoaFu我很感谢帮助!现在我只是在索引1和最后一个对象上使用对象来获得我需要的东西,但是我会查看正则表达式......它似乎更可行。 – FreeAppl3

2

的NSString具有与签名的方法:

componentsSeparatedByString: 

它返回部件作为其结果的数组。像这样使用它:

NSArray *components = [myNSString componentsSeparatedByString:@" "]; 

[components objectAtIndex:0]; //should be SiteName 
[components objectAtIndex:1]; // should be http://Link.com 

祝你好运。

+0

实际上,如果存在多个空格字符分隔组件,那么它将不会获取该站点。 – zaph

+0

非常感谢你!我知道这很简单,因为几行代码根本无法弄清楚如何得到它们......这两个答案都可以工作!我非常感谢帮助! – FreeAppl3