Đối với iOS, mã sau sẽ hoạt động đối với mã số. Nó phải là tương đối dễ dàng để mở rộng đến những cái tên như &
...
-(NSString*)unescapeHtmlCodes:(NSString*)input {
NSRange rangeOfHTMLEntity = [input rangeOfString:@"&#"];
if(NSNotFound == rangeOfHTMLEntity.location) {
return input;
}
NSMutableString* answer = [[NSMutableString alloc] init];
[answer autorelease];
NSScanner* scanner = [NSScanner scannerWithString:input];
[scanner setCharactersToBeSkipped:nil]; // we want all white-space
while(![scanner isAtEnd]) {
NSString* fragment;
[scanner scanUpToString:@"&#" intoString:&fragment];
if(nil != fragment) { // e.g. '& B'
[answer appendString:fragment];
}
if(![scanner isAtEnd]) { // implicitly we scanned to the next '&#'
int scanLocation = (int)[scanner scanLocation];
[scanner setScanLocation:scanLocation+2]; // skip over '&#'
int htmlCode;
if([scanner scanInt:&htmlCode]) {
char c = htmlCode;
[answer appendFormat:@"%c", c];
scanLocation = (int)[scanner scanLocation];
[scanner setScanLocation:scanLocation+1]; // skip over ';'
} else {
// err ?
}
}
}
return answer;
}
Một số mã đơn vị kiểm tra ...
-(void)testUnescapeHtmlCodes {
NSString* expected = @"A & B";
NSString* actual = [self unescapeHtmlCodes:@"A & B"];
STAssertTrue([expected isEqualToString:actual], @"actual = %@", actual);
expected = @"& B";
actual = [self unescapeHtmlCodes:@"& B"];
STAssertTrue([expected isEqualToString:actual], @"actual = %@", actual);
expected = @"A &";
actual = [self unescapeHtmlCodes:@"A &"];
STAssertTrue([expected isEqualToString:actual], @"actual = %@", actual);
}
Nguồn
2012-05-04 02:53:29
tôi đã làm như vậy ... nhưng là có cách nào để BUILTIN làm điều này ... – nbojja
@nbojja Bạn muốn xây dựng bao nhiêu hơn? Nếu bạn lo lắng, hãy thêm một phương thức thực hiện điều này làm một danh mục trên NSString và sau đó nó được tích hợp. – Abizern
@Abizern: Nhiều ngôn ngữ có các phương thức mã hóa và giải mã các thực thể HTML, Obj-C thiếu điều này và nhiều những điều lập trình viên cho phép từ năm 2002. Tìm kiếm và thay thế là một thay thế nghèo nàn, bởi vì bạn sẽ phải dành một chút thời gian để biết bạn có được tất cả các thực thể. –