字符串@"\EOP"
在\E
是與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);
字符串從哪裏來? –
一個問題:爲什麼你使用同一個名字'str'? – Bhavin
@MartinR字符串來自數據庫,但我檢查設置靜態字符串str = @「\ EOP」;但仍然無法工作。 – Nikunj