NSString @“\” adding backslash character objective-c

前端 未结 5 2059
臣服心动
臣服心动 2021-01-04 11:27

Does anyone know of an easy way to add a single backslash (\\) to a NSString in Objective-C? I am trying to have a NSString *temp = @\"\\/Dat

相关标签:
5条回答
  • 2021-01-04 11:59

    This code does give the requested output:

    NSString *temp = @"\\/Date(100034234)\\/";
    NSLog(@"%@",temp);
    

    However I had an issue with my JSON toolkit (SBJSON) that replaced all occurrances of "\\" with "\\\\", which did cause issues as described in the other answers and the comments.

    The result was a string looking like:

    @"\\\\/Date(100034234)\\\\/"
    

    See my answer here

    The solution was using:

    temp = [temp stringByReplacingOccurancesOfString:@"\\\\" withString:@"\\"];
    
    0 讨论(0)
  • 2021-01-04 12:02

    The strings and NSLog are working fine for me (iPhone SDK 3.1.2 and Xcode 3.2.1):

    NSLog(@"\\"); // output is one backslash
    NSLog(@"\\\\"); // output is two backslashes
    NSLog(@"\\/Date(100034234)\\/"); // output is \/Date(100034234)\/
    

    See this answer.

    0 讨论(0)
  • 2021-01-04 12:14

    This is a bug in NSLog. I found a mailing list archive with a message dated in 2002 of someone that filed a bug for this here. The person also said this:

    Nothing has been done as far as I can tell. I don't understand how they've done it, but the escaping does work for the string, just not for NSLog.

    So I guess you will have to come up with your own implementation of a log message if you really want backslashes.

    0 讨论(0)
  • 2021-01-04 12:20

    The string @"\\" is a single backslash, @"\\\\" is a double backslash

    0 讨论(0)
  • 2021-01-04 12:20

    Where you want a \ add or remove. just \\ on that place.

    0 讨论(0)
提交回复
热议问题