string 在 NSString 中转义换行符和双引号等字符的最佳方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/579672/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 00:22:57  来源:igfitidea点击:

Best way to escape characters like newline and double-quote in NSString

cocoamacosstring

提问by dreamlax

Say I have an NSString (or NSMutableString) containing:

假设我有一个 NSString(或 NSMutableString)包含:

I said "Hello, world!".
He said "My name's not World."

What's the best way to turn that into:

把它变成的最好方法是什么:

I said \"Hello, world!\".\nHe said \"My name\'s not World.\"

Do I have to manually use -replaceOccurrencesOfString:withString:over and over to escape characters, or is there an easier way? These strings may contain characters from other alphabets/languages.

我是否必须-replaceOccurrencesOfString:withString:一遍又一遍地手动使用来转义字符,还是有更简单的方法?这些字符串可能包含来自其他字母表/语言的字符。

How is this done in other languages with other string classes?

这是如何在其他语言中使用其他字符串类完成的?

采纳答案by danielpunkass

I don't think there is any built-in method to "escape" a particular set of characters.

我认为没有任何内置方法可以“转义”一组特定的字符。

If the characters you wish to escape is well-defined, I'd probably stick with the simple solution you proposed, replacing the instances of the characters crudely.

如果您希望转义的字符定义明确,我可能会坚持使用您提出的简单解决方案,粗略地替换字符的实例。

Be warned that if your source string already has escaped characters in it, then you'll probably want to avoid "double-escaping" them. One way of achieving this would be to go through and "unescape" any escaped character strings in the string before then escaping them all again.

请注意,如果您的源字符串中已经包含转义字符,那么您可能希望避免“双重转义”它们。实现这一点的一种方法是在再次转义之前遍历并“取消转义”字符串中的任何转义字符串。

If you need to support a variable set of escaped characters, take a look at the NSScanner methods "scanUpToCharactersFromSet:intoString:" and "scanCharactersFromSet:intoString:". You could use these methods on NSScanner to cruise through a string, copying the parts from the "scanUpTo" section into a mutable string unchanged, and copying the parts from a particular character set only after escaping them.

如果您需要支持一组可变的转义字符,请查看 NSScanner 方法“scanUpToCharactersFromSet:intoString:”和“scanCharactersFromSet:intoString:”。您可以在 NSScanner 上使用这些方法来浏览字符串,将“scanUpTo”部分中的部分复制到不变的可变字符串中,并仅在转义它们后才从特定字符集中复制这些部分。

回答by Niklas Alvaeus

stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding

stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding

回答by danielpunkass

This will escape double quotes in NSString:

这将转义 NSString 中的双引号:

NSString *escaped = [originalString stringByReplacingOccurrencesOfString:@"\"" withString:@"\\""];

So you need to be careful and also escape the escape character...

所以你需要小心,并逃脱转义字符......

回答by Seth Kingsley

I think in cases like these, it's useful to operate on a character at a time, either in UniChars or UTF8 bytes. If you're using UTF-8, then vis(3)will do most of the work for you (see below). Can I ask why you want to escape a single-quote within a double-quoted string? How are you planning to handle multi-byte characters? In the example below, I'm using UTF-8, encoding 8-bit characters using C-Style octal escapes. This can also be undone by unvis(3).

我认为在这种情况下,一次操作一个字符很有用,无论是 UniChars 还是 UTF8 字节。如果您使用的是 UTF-8,那么vis(3)将为您完成大部分工作(见下文)。我能问一下为什么要在双引号字符串中转义单引号吗?您打算如何处理多字节字符?在下面的示例中,我使用 UTF-8,使用 C 样式八进制转义对 8 位字符进行编码。这也可以通过 撤消unvis(3)

#import <Foundation/Foundation.h>
#import <vis.h>

@interface NSString (Escaping)

- (NSString *)stringByEscapingMetacharacters;

@end

@implementation NSString (Escaping)

- (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];
}

@end

int
main(int argc, const char *argv[])
{
    NSAutoreleasePool *pool = [NSAutoreleasePool new];

    NSLog(@"%@", [@"I said \"Hello, world!\".\nHe said \"My name's not World.\"" stringByEscapingMetacharacters]);

    [pool drain];
    return 0;
}

回答by pheedsta

This is a snippet I have used in the past that works quite well:

这是我过去使用过的一个片段,效果很好:

- (NSString *)escapeString:(NSString *)aString
{
    NSMutableString *returnString = [[NSMutableString alloc] init];

    for(int i = 0; i < [aString length]; i++) {

        unichar c = [aString characterAtIndex:i];

        // if char needs to be escaped
        if((('\' == c) || ('\'' == c)) || ('"' == c)) {
            [returnString appendFormat:@"\%c", c];            
        } else {
            [returnString appendFormat:@"%c", c];
        }
    }

    return [returnString autorelease];   
}

回答by fursund

Do this:

做这个:

NSString * encodedString = (NSString *)CFURLCreateStringByAddingPercentEscapes(
    NULL,
    (CFStringRef)unencodedString,
    NULL,
    (CFStringRef)@"!*'();:@&=+$,/?%#[]",
    kCFStringEncodingUTF8 );

Reference: http://simonwoodside.com/weblog/2009/4/22/how_to_really_url_encode/

参考:http: //simonwoodside.com/weblog/2009/4/22/how_to_really_url_encode/

回答by Marc Charbonneau

You might even want to look into using a regex library (there are a lot of options available, RegexKit is a popular choice). It shouldn't be too hard to find a pre-written regex to escape strings that handles special cases like existing escaped characters.

您甚至可能想考虑使用正则表达式库(有很多可用的选项,RegexKit 是一个流行的选择)。找到一个预先编写的正则表达式来转义处理现有转义字符等特殊情况的字符串应该不会太难。