Remove part of an NSString

Michael Amici picture Michael Amici · Dec 12, 2010 · Viewed 12.8k times · Source

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.

Answer

Tommy picture Tommy · Dec 12, 2010

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:.