Remove part of an NSString

感情迁移 提交于 2019-12-05 12:37:24

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

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.

David Karlsson

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