簡體   English   中英

從 C/Obj-C 到 javascript 的 UTF8 字符串中的 Escaping 變音符號

[英]Escaping diacritics in a UTF8 string from C/Obj-C to javascript

首先,簡要解釋一下我為什么要這樣做:

我正在從 XML 加載字符串,並使用這些字符串與現有的 javascript 函數進行交互。 我需要轉義它們,只是因為我使用的是 webview 的 stringByEvaluatingJavaScriptFromString 方法。

我正在使用這個轉義 function:

- (NSString *) stringByEscapingMetacharacters
{    
    const char *UTF8Input = [self UTF8String];
    char *UTF8Output = [[NSMutableData dataWithLength:strlen(UTF8Input) * 4 + 1  /* Worst case */] mutableBytes];
    char ch, *och = UTF8Output;

    while ((ch = *UTF8Input++))
        if (ch == '\'' || ch == '\'' || ch == '\\' || ch == '"')
        {
            *och++ = '\\';
            *och++ = ch;
        } 
        else if (isascii(ch))
            och = vis(och, ch, VIS_NL | VIS_TAB | VIS_CSTYLE, *UTF8Input);
        else
            och+= sprintf(och, "\\%03hho", ch);
    return [NSString stringWithUTF8String:UTF8Output];
}

它工作正常,除了變音符號。 例如,“é”顯示為“é”

那么,我怎樣才能擺脫變音符號呢?

您需要實施正確的 UTF-8 序列擒縱機構。 像這樣的東西:

if (ch == '\'' || ch == '\'' || ch == '\\' || ch == '"')
{
    *och++ = '\\';
    *och++ = ch;
} 
else if (((unsigned char)ch & 0xe0) == 0xc0) // 2 byte utf8 sequence
{
    *och++ = ch;
    *och++ = UTF8Input++;
}
else if (((unsigned char)ch & 0xf0) == 0xe0)  // 3 byte utf8 sequence
{
    *och++ = ch;
    *och++ = UTF8Input++;
    *och++ = UTF8Input++;
}
else if (isascii(ch))
     och = vis(och, ch, VIS_NL | VIS_TAB | VIS_CSTYLE, *UTF8Input);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM