Add backslash to String in Objective-c

那年仲夏 提交于 2019-11-26 22:10:21

问题


I have a problem identical to this problem here.

I even want to encode the same infromation as him (it's a date/time for asp.net)...

When ever I try to add a backslash i get two backslashes since I used \.

Everyone in the thread above has claimed that this is a problem with NSLog and that NSString does treat \\ as a \. I have checked this further by using a packet sniffer to examine the packets I'm sending to the webserver and I can confirm that it is transmitting a double backslash instead of a single backslash.

Does anyone know how to add a backslash to a NSString?


回答1:


The strings and NSLog are working fine for me:

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

What am I missing?




回答2:


Try this:

yourStr =  [yourStr stringByReplacingOccurrencesOfString:@"\\\\" withString:@"\\"];
NSLog(@"%@", yourStr);

I had the same problem, turned out that my JSON Parser replaced all occurrances of "\\" with "\\\\", so when I NSLogged my original code like this:

NSString *jsonString = [myJSONStuff JSONRepresentation];
NSLog(@"%@", jsonString);

This is what I got:

{TimeStamp : "\\/Date(12345678)\\/"}

However, the string itself contained FOUR backslashes (but only 2 of them are printed by NSLog).

This is what helped me:

NSString *jsonString = [myJSONStuff JSONRepresentation];
jsonString = [jsonString stringByReplacingOccurrencesOfString:@"\\\\" withString:@"\\"];
NSLog(@"%@", jsonString);

The result:

{TimeStamp : "\/Date(12345678)\/"}



来源:https://stackoverflow.com/questions/2116669/add-backslash-to-string-in-objective-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!