Separate 1 NSString into two NSStrings by whiteSpa

2019-02-22 20:44发布

问题:

I have an NSString which initially looked like <a href="http://link.com"> LinkName</a>. I removed the html tags and now have an NSString that looks like

http://Link.com   SiteName

how can I separate the two into different NSStrings so I would have

http://Link.com

and

SiteName

I specifically want to show the SiteName in a label and just use the http://Link.com to open in a UIWebView but I can't when it is all one string. Any suggestions or help is greatly appreciated.

回答1:

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'


回答2:

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.