\E
字符串@"\EOP"
中是 ASCII 码(或 Unicode)为 27 的字符,它是一个控制字符。
我不知道转义字符串中所有控制字符的内置方法。以下代码用于NSScanner
定位控制字符,并使用查找表替换它们。如果可能,控制字符将替换为“字符转义码”,例如“\r”或“\n”,否则替换为“\x”,后跟十六进制代码。
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);