在 Objective-C 中解析 html 的代碼

來源:互聯網
上載者:User

轉自: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
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.