在NSString中搜索未知字符串

时间:2014-12-10 20:11:19

标签: objective-c nsstring

在我的iOS应用中,我获得了NSString网站的完整HTML。沿着这条线向下,我需要在代码中NSString *pageTitle。因此,理想情况下,我想要搜索NSString <title>Title of page</title>

我想象一下我需要做什么,是找<title>然后把它作为</title>之后的部分。但是,我不知道如何正确地做到这一点。有什么想法吗?

这是我到目前为止所做的:

NSString *string = @"<html><head><title>Title of page</title></head><body></body></html>";
if ([string rangeOfString:@"<title>"].location == NSNotFound) {
    NSLog(@"string does not contain a title");
} else {
    NSLog(@"string contains a title!");
}

2 个答案:

答案 0 :(得分:2)

每当你需要做这样的事情时,NSScanner就是要使用的工具。

NSString *string = @"<html><head><title>Title of page</title></head><body></body></html>";

// Set up convenience variables for the start and end tag;
NSString *startTag = @"<title>";
NSString *endTag = @"</title>";

// Declare a string variable which will eventually contain the title
NSString *title;

// Create a scanner with the string you want to scan.
NSScanner *scanner = [NSScanner scannerWithString:string];

// Scan up to the <title>, throw away the result.
[scanner scanUpToString:startTag intoString:nil];

// Scan <title>, throw away the result.
[scanner scanString:startTag intoString:nil];

// Scan up to the </title> tag, put the characters into `title`
[scanner scanUpToString:endTag intoString:&title];

// Just to show that I'm not lying, print out the scanned title to the console.
NSLog(@"Title is: %@", title);

答案 1 :(得分:0)

您可以这样做以获得标题:

NSRange searchFromRange = [string rangeOfString:@"<title>"];
NSRange searchToRange = [string rangeOfString:@"</title>"];
NSString *title= [string substringWithRange:NSMakeRange(searchFromRange.location+searchFromRange.length, searchToRange.location-searchFromRange.location-searchFromRange.length)];
NSLog(@"title=%@",title);