Iphone 用空格将1个NSString分隔为两个NSString
我有一个Iphone 用空格将1个NSString分隔为两个NSString,iphone,nsstring,whitespace,Iphone,Nsstring,Whitespace,我有一个NSString,它最初看起来像。我删除了html标记,现在有了一个 http://Link.com SiteName 如何将这两个字符串分隔为不同的NSStrings,以便 http://Link.com 及 我特别想在标签中显示SiteName,只需使用http://Link.com在UIWebView中打开,但当它都是一个字符串时,我无法打开。非常感谢您的任何建议或帮助。NSString有一个带有签名的方法: componentsSeparatedByString: 它返
NSString
,它最初看起来像
。我删除了html标记,现在有了一个
http://Link.com SiteName
如何将这两个字符串分隔为不同的NSString
s,以便
http://Link.com
及
我特别想在标签中显示
SiteName
,只需使用http://Link.com
在UIWebView中打开
,但当它都是一个字符串时,我无法打开。非常感谢您的任何建议或帮助。NSString有一个带有签名的方法:
componentsSeparatedByString:
它返回一个组件数组作为其结果。像这样使用它:
NSArray *components = [myNSString componentsSeparatedByString:@" "];
[components objectAtIndex:0]; //should be SiteName
[components objectAtIndex:1]; // should be http://Link.com
祝你好运
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'
http: 'http://link.com'
site: 'Link Name'
另外,处理带有嵌入空间的站点名称时,请使用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);
如果组件之间有多个空格字符分隔,那么可能的副本实际上不会得到该站点。非常感谢!我知道这很简单,因为只有几行代码无法理解如何获取它们。。。这两个答案都有效!我非常感谢你的帮助!!!是的,你的权利,它在一些“网站名”工作,但有些是间隔以及像“网站名”,所以我遇到了另一个问题。。。但是如果没有其他方法的话,我可以使用一些肮脏的代码来绕开它。你可能最好使用正则表达式。谢谢@CocoaFu,我感谢你的帮助!现在我只使用了索引1中的object和最后一个object来获得我需要的东西,但我将研究正则表达式。。这似乎更可行。
http: 'http://link.com'
site: 'Link Name'