如何在NSString中删除字符'\'?

时间:2014-06-24 11:11:47

标签: ios objective-c

如何在NSString IOS中删除字符'\'

例如,

NSString *abc = @"bmcvn\nmsf;

我试过了:

NSString *stri = @"\rdffsdf";
NSString *str = [stri stringByReplacingOccurrencesOfString:@"\\" withString:@"123"];
NSLog(str);

但它没有取代

4 个答案:

答案 0 :(得分:2)

你不能在字符串“\ rdffsdf”中替换“\”,因为它是单字符的两个字符表示“\ _ r \ n”的一部分,其十六进制值为0x0d(十进制13)。这是“回车”字符。

当字符串中需要回车字符(0x0d)时,它将输入为“\ r”。同样常见的是两个字符序列换行符“\ n”(0X0a),水平制表符“\ t”(0X09)和最后反斜杠“\”(0x5c)。

反斜杠案例:

NSString *stri = @"\\rdffsdf";
NSString *str = [stri stringByReplacingOccurrencesOfString:@"\\" withString:@"123"];
NSLog(@"str: %@", str);

NSLog输出:

  

str:123rdffsdf

答案 1 :(得分:2)

注意替换反斜杠char

之间的区别
NSString *original = @"foo\\bar";
NSLog(@"%@", original); // Prints: foo\bar
NSString *replaced = [original stringByReplacingOccurrencesOfString:@"\\" withString:@""];
NSLog(@"%@", replaced); // Prints: foobar

并替换使用反斜杠(\ r,\ n,\ t,...)表示的字符:

NSString *original = @"thisIsCarriageReturn\rRightThere";
NSLog(@"%@", original); // Prints: thisIsCarriageReturn
                        //         RightThere
NSString *replaced = [original stringByReplacingOccurrencesOfString:@"\r" withString:@""];
NSLog(@"%@", replaced); // Prints: thisIsCarriageReturnRightThere

答案 2 :(得分:1)

NSString *s = @"foo/bar:baz.foo";
NSCharacterSet *doNotWant = [NSCharacterSet characterSetWithCharactersInString:@"/:."];
s = [[s componentsSeparatedByCharactersInSet: doNotWant] componentsJoinedByString: @""];
NSLog(@"%@", s); // => foobarbazfoo

Replace multiple characters in a string in Objective-C?

答案 3 :(得分:0)

由于反斜杠字符是转义字符,因此您必须编写其中两个字符。

- (NSString *)sanitizeString:(NSString *)string {
    NSCharacterSet* illegalCharacters = [NSCharacterSet characterSetWithCharactersInString:@"\n"];
    return [[string componentsSeparatedByCharactersInSet: illegalCharacters] componentsJoinedByString:@"n"];
}