Delete part of NSString

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 need only the first part (before the <a href ), and I cannot figure out how to remove the second part.

I tried a ton, but it didn’t work.

+5
source share
3 answers

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, there are two corresponding methods: substringToIndex: and rangeOfString:.

+18
source

In the NSString class description, there is a section Searching for characters and substrings , which lists some useful methods.

And in the string programming guide. There is a section Searching, comparing and sorting strings.

I am not going to indicate these links. You said you couldn't find the methods, so here are a few links to help you find out where to look. Learning how to read the documentation is part of learning the Cocoa and Cocoa -Touch Framework methods.

+3
source

You can use something similar to this modified version of what has been posted as an answer to a similar question here https://stackoverflow.com/a/464829/ This will take your HTML line and cross out the formatting. Just change the while part to remove the regex of what you want to remove:

 -(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; } 
0
source

All Articles