2011-10-12 31 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