gpt4 book ai didi

ios - 为什么 NSScanner 会丢弃空格?

转载 作者:行者123 更新时间:2023-11-29 10:52:41 26 4
gpt4 key购买 nike

我正在构建一个简单的 HTML 到 NSAttributedString 的转换方法,但出于某种原因,NSScanner 类在找到标记后丢弃了一个空格。例如,如果 html 格式的字符串是 @"This is a <b>bold</b> word" ,结果是@"This is a boldword"。为什么我的方法会丢失结束标记后的空格?你觉得我的方法有什么可疑之处吗?

+ (NSAttributedString *)attributedStringFromHtmlString:(NSString *)htmlString {

NSMutableAttributedString *attributedString;
NSRange range;
NSScanner *htmlScanner;
NSMutableString *strippedString;

BOOL boldFlag = NO;
BOOL italicFlag = NO;
BOOL underlineFlag = NO;

htmlScanner = [NSScanner scannerWithString:htmlString];
while (![htmlScanner isAtEnd]) {
NSString *firstPass, *tagString;
NSCharacterSet *openTagSet;
NSCharacterSet *closeTagSet;
NSMutableAttributedString *newAttributedString;

openTagSet = [NSCharacterSet characterSetWithCharactersInString:@"<"];
closeTagSet = [NSCharacterSet characterSetWithCharactersInString:@">"];
newAttributedString = [[NSMutableAttributedString alloc] init];

if ([htmlScanner scanUpToCharactersFromSet:openTagSet intoString:&firstPass]) {
[newAttributedString appendAttributedString:[[NSAttributedString alloc] initWithString:firstPass]];
[attributedString appendAttributedString:newAttributedString];
}

// Either we hit a '<' or we're at the end of the text.
if (![htmlScanner isAtEnd]) {
[htmlScanner scanCharactersFromSet:openTagSet intoString:NULL];
[htmlScanner scanUpToCharactersFromSet:closeTagSet intoString:&tagString];
[htmlScanner scanCharactersFromSet:closeTagSet intoString:NULL];
tagString = [tagString lowercaseString];

if ([tagString isEqual:@"b"]) {
boldFlag = YES;
}
else if ([tagString isEqual:@"/b"]) {
boldFlag = NO;
}
else if ([tagString isEqual:@"h"]) {
boldFlag = YES;
}
else if ([tagString isEqual:@"/h"]) {
boldFlag = NO;
}
else if ([tagString isEqual:@"i"]) {
italicFlag = YES;
}
else if ([tagString isEqual:@"/i"]) {
italicFlag = NO;
}
else if ([tagString isEqual:@"br /"]) {
[attributedString appendAttributedString:[[NSAttributedString alloc] initWithString:@"\n"]];
}
}
}

range.location = 0;
range.length = [attributedString length];

return attributedString;
}

提前感谢您的智慧!

最佳答案

因为 NSScanner 的默认值 charactersToBeSkipped都是空白字符。

尝试将其设置为零:

htmlScanner.charactersToBeSkipped = nil;

关于ios - 为什么 NSScanner 会丢弃空格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19800854/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com