NSString @“\” adding backslash character objective-c

送分小仙女□ 提交于 2019-12-18 21: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 = @"\/Date(100034234)\/";

I am able to get a double backslash or no backslash, but unable to get a single backslash. Any help would be appreciated. Thanks


回答1:


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




回答2:


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.




回答3:


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.




回答4:


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:@"\\"];



回答5:


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



来源:https://stackoverflow.com/questions/1281141/nsstring-adding-backslash-character-objective-c

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