HTML character decoding in Objective-C / Cocoa Touch

后端 未结 13 2113
我寻月下人不归
我寻月下人不归 2020-11-22 10:24

First of all, I found this: Objective C HTML escape/unescape, but it doesn\'t work for me.

My encoded characters (come from a RSS feed, btw) look like this: &a

13条回答
  •  醉梦人生
    2020-11-22 11:16

    you can use just this function to solve this problem.

    + (NSString*) decodeHtmlUnicodeCharactersToString:(NSString*)str
    {
        NSMutableString* string = [[NSMutableString alloc] initWithString:str];  // #&39; replace with '
        NSString* unicodeStr = nil;
        NSString* replaceStr = nil;
        int counter = -1;
    
        for(int i = 0; i < [string length]; ++i)
        {
            unichar char1 = [string characterAtIndex:i];    
            for (int k = i + 1; k < [string length] - 1; ++k)
            {
                unichar char2 = [string characterAtIndex:k];    
    
                if (char1 == '&'  && char2 == '#' ) 
                {   
                    ++counter;
                    unicodeStr = [string substringWithRange:NSMakeRange(i + 2 , 2)];    
                    // read integer value i.e, 39
                    replaceStr = [string substringWithRange:NSMakeRange (i, 5)];     //     #&39;
                    [string replaceCharactersInRange: [string rangeOfString:replaceStr] withString:[NSString stringWithFormat:@"%c",[unicodeStr intValue]]];
                    break;
                }
            }
        }
        [string autorelease];
    
        if (counter > 1)
            return  [self decodeHtmlUnicodeCharactersToString:string]; 
        else
            return string;
    }
    

提交回复
热议问题