替换字符串中的unicode值 [英] Replace unicode value in string

查看:126
本文介绍了替换字符串中的unicode值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串@"\EOP".我想把这个支付给用户.但是,当我在文本字段中显示此字符串时,它仅显示OP.我尝试在调试时在控制台中打印它,并显示¿OP

I have a string @"\EOP". I want to dislpay this to user. But when i display this string in textfield, It shows only OP. I tried to print that in console while debugging and it shows ¿OP

所以\E是unicode值,这就是为什么它存在一些编码问题的原因.我可以通过以下方法解决此问题:

So \E is unicode value and that's why it's having some issue of encoding. I can fix this issue by:

NSString *str=[str stringByReplacingOccurrencesOfString:@"\E" withString:@"\\E"];

以此显示完美的字符串@"\EOP".

With this it will display perfect string @"\EOP".

这是我的问题,可能还有更多像\E这样的字符,例如\u.如何为所有这些字符实施一个修补程序?

Here my issue is that there can be many more characters same like \E for example \u. How can I implement one fix for all these kind of characters?

推荐答案

\E是具有ASCII码(或Unicode)27的字符, 这是一个控制字符.

\E in the string @"\EOP" is the character with the ASCII-code (or Unicode) 27, which is a control character.

我不知道一种内置方法来转义字符串中的所有控制字符. 以下代码使用NSScanner定位控制字符,并将其替换 使用查找表.控制字符替换为字符转义码" 例如"\ r"或"\ n"(如果可能的话),否则用"\ x"后跟十六进制代码.

I don't know of a built-in method to escape all control characters in a string. The following code uses NSScanner to locate the control characters, and replaces them using a lookup-table. The control characters are replaced by "Character Escape Codes" such as "\r" or "\n" if possible, otherwise by "\x" followed by the hex-code.

NSString *str = @"\EOP";

NSCharacterSet *controls = [NSCharacterSet controlCharacterSet];
static char *replacements[] = {
    "0", NULL, NULL, NULL, NULL, NULL, NULL, "\\a",
    "\\b", "\\t", "\\n", "\\v", "\\f", "\\r", NULL, NULL,
    NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
    NULL, NULL, NULL, "\\e"};

NSScanner *scanner = [NSScanner scannerWithString:str];
[scanner setCharactersToBeSkipped:nil];
NSMutableString *result = [NSMutableString string];

while (![scanner isAtEnd]) {
    NSString *tmp;
    // Copy all non-control characters verbatim:
    if ([scanner scanUpToCharactersFromSet:controls intoString:&tmp]) {
        [result appendString:tmp];
    }
    if ([scanner isAtEnd])
        break;
    // Escape all control characters:
    if ([scanner scanCharactersFromSet:controls intoString:&tmp]) {
        for (int i = 0; i < [tmp length]; i++) {
            unichar c = [tmp characterAtIndex:i];
            char *r;
            if (c < sizeof(replacements)/sizeof(replacements[0])
                && (r = replacements[c]) != NULL) {
                // Replace by well-known character escape code:
                [result appendString:@(r)];
            } else {
                // Replace by \x<hexcode>:
                [result appendFormat:@"\\x%02x", c];
            }
        }
    }

}

NSLog(@"%@", result);

这篇关于替换字符串中的unicode值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆