轉自:http://www.cocoachina.com/macdev/objc/2010/1104/2296.html
本段在 Objective-C 中解析 html 的代碼由 CocoaChina 會員 “月華如水” 分享,希望對開發人員們有所協助
#import "StringChuLi.h"/*項目作用:連結網路解析html */@implementation StringChuLi//訪問網頁源碼-(NSString *)urlString:(NSString *)value{NSURL *url = [NSURL URLWithString:value];NSData *data = [NSData dataWithContentsOfURL:url]; //解決中文亂碼,用GBKNSStringEncoding enc = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000); NSString *retStr = [[NSString alloc] initWithData:data encoding:enc];return retStr;}/* 作用:截取從value1到value2之間的字串 str:要處理的字串 value1:左邊匹配字串 value2:右邊匹配字串 */-(NSString *)str:(NSString *)str value1:(NSString *)value1 value2:(NSString *)value2{//i:左邊匹配字串在str中的下標int i;//j:右邊匹配字串在str1中的下標int j;//該類可以通過value1匹配字串NSRange range1 = [str rangeOfString:value1];//判斷range1是否匹配到字串if(range1.length>0){//把其轉換為NSStringNSString *result1 = NSStringFromRange(range1);i = [self indexByValue:result1];//原因:加上匹配字串的長度從而獲得正確的下標i = i+[value1 length];}//通過下標,刪除下標以前的字元NSString *str1 = [str substringFromIndex:i];NSRange range2 = [str1 rangeOfString:value2];if(range2.length>0){NSString *result2 = NSStringFromRange(range2);j = [self indexByValue:result2];}NSString *str2 = [str1 substringToIndex:j];return str2;}//過濾獲得的匹配資訊的下標-(int)indexByValue:(NSString *)str{//使用NSMutableString類,它可以實現追加NSMutableString *value = [[NSMutableString alloc] initWithFormat:@""];NSString *colum2 = @"";int j = 0;//遍曆出下標值for(int i=1;i<[str length];i++){NSString *colum1 = [str substringFromIndex:i];[value appendString:colum2];colum2 = [colum1 substringToIndex:1];if([colum2 isEqualToString:@","]){j = [value intValue];break;}}[value release];return j;}@end