问题
I have an NSString as follows:
<img alt="996453912" src="http://d2gg0uigdtw9zz.cloudfront.net/large/996453912.jpg" /><a href="http://www.dealcatcher.com/shop4tech-coupons">Shop4Tech Coupons</a>
I only need the first part (before the <a href
part), and I cannot figure out how to remove the second part.
I have tried a ton, but it has not worked.
回答1:
Use something like:
NSRange rangeOfSubstring = [string rangeOfString:@"<a href"];
if(rangeOfSubstring.location == NSNotFound)
{
// error condition — the text '<a href' wasn't in 'string'
}
// return only that portion of 'string' up to where '<a href' was found
return [string substringToIndex:rangeOfSubstring.location];
So the two relevant methods are substringToIndex: and rangeOfString:.
回答2:
There is a section in the NSString Class reference about Finding Characters and Substrings which lists some helpful methods.
And in the String Programming Guide There is a section on Searching, Comparing and Sorting Strings.
I'm not being shirty in pointing out these links. You've said that you've couldn't find methods so here are a couple of references to help you know where to look. Learning how to read the documentation is part of learning how to use the Cocoa and Cocoa-Touch Frameworks.
回答3:
You could use something similar to this modified version of what was posted as an answer to a similar question here https://stackoverflow.com/a/4886998/283412. This will take your HTML string and strip out the formatting. Just modify the while part to remove the regex of what you want to strip:
-(void)myMethod
{
NSString* htmlStr = @"<some>html</string>";
NSString* strWithoutFormatting = [self stringByStrippingHTML:htmlStr];
}
-(NSString *)stringByStrippingHTML:(NSString*)str
{
NSRange r;
while ((r = [str rangeOfString:@"<[^>]+>" options:NSRegularExpressionSearch]).location != NSNotFound)
{
str = [str stringByReplacingCharactersInRange:r withString:@""];
}
return str;
}
来源:https://stackoverflow.com/questions/4423248/remove-part-of-an-nsstring