Separate 1 NSString into two NSStrings by whiteSpace

我的未来我决定 提交于 2019-12-01 18:12:00
NSString *s = @"http://Link.com   SiteName";
NSArray *a = [s componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
NSLog(@"http: '%@'", [a objectAtIndex:0]);
NSLog(@"site: '%@'", [a lastObject]);

NSLog output:

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

Bonus, handle a site name with an embedded space with a 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 output:

http: 'http://link.com'
site: 'Link Name'
DexterW

NSString has a method with the signature:

componentsSeparatedByString:

It returns an array of components as its result. Use it like this:

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

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

Good luck.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!