2

我从带有反斜杠字符的 json 响应中得到一个字符串作为字符串。我想从 url 中删除 '\' 字符。我建立了代码,但它不起作用。代码在这里:

 NSString *responseData = [[NSString alloc]initWithData:[NSData dataWithContentsOfURL:url] encoding:NSUTF8StringEncoding];
    NSString* encodedString = [responseData stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        NSLog(@"Response ==> %@" ,encodedString);

       // here encodedString is a url which is showing crctly in output and need to trim the \ character.

       // NSString* str = [NSString stringWithFormat: @"encodedString"];
       // str = [str stringByReplacingOccurrencesOfString:@"?" withString:@""];
       // NSLog(@"Response ==> %@" , str);

    encodedString = [encodedString stringByReplacingOccurrencesOfString:@"\\" withString:@""];
        NSLog(@"Response ==> %@" ,encodedString);

但我无法删除字符。

4

3 回答 3

5

如果要删除空格和\字符,最好将它们从responseData.

NSString *responseData = [[NSString alloc]initWithData:[NSData dataWithContentsOfURL:url] encoding:NSUTF8StringEncoding];

responseData = [responseData stringByReplacingOccurrencesOfString:@" " withString:@""];
responseData = [responseData stringByReplacingOccurrencesOfString:@"\\" withString:@""];
NSString* encodedString = [responseData stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
于 2013-03-08T08:14:32.303 回答
4

试试这个:

    NSCharacterSet *doNotWant = [NSCharacterSet characterSetWithCharactersInString:@"\\"];
    encodedString = [[encodedString componentsSeparatedByCharactersInSet: doNotWant] componentsJoinedByString: @""];
    NSLog(@"%@", encodedString);

希望这会有所帮助

于 2013-03-08T08:06:39.477 回答
0

试试这个方法;

假设您的字符串包含一个 \,在字符串中使用双倍作为转义下一个 \

NSMutableString *string=[NSMutableString stringWithString:@"hi this i\\s good"];
//NSMutableString *string=[NSMutableString stringWithString:encodedString];

[string replaceOccurrencesOfString:@"\\" withString:@"" options:1 range:NSMakeRange(0, string.length)];

NSLog(@"%@",string);
于 2013-03-08T08:11:24.623 回答