How do I escape a Unicode character in my Objective-C source code?

杀马特。学长 韩版系。学妹 提交于 2019-12-17 16:24:37

问题


I feel incredibly stupid for asking this, but the documentation and Google are giving me no love at all.

I have a Unicode character I want to insert into a string literal in the source code of my iPhone app. I know its hex value. What is the proper escape sequence to use? And for that matter, what obvious source of information am I overlooking that would have told me this?


回答1:


Example:

NSString *stuff = @"The Greek letter Beta looks like this: \u03b2, and the emoji for books looks like this: \U0001F4DA";



回答2:


If you don't want to put it directly in your string you can use a format specifier like this:

[string stringByAppendingFormat:@"%C", 0x2665];



回答3:


A more modern approach:

I'm not sure when this feature was added to the language, but as of 2015, at least, Objective-C string literals can contain any Unicode character. For instance, I mark my log lines with emoji because their distinctive colors are an easier way for me to pick them out:

So, if you have the character and not just the code point, and you want to use it in a static string and not dynamically generate it, this is a great approach, since you instantly know what character you're using just by looking at it.




回答4:


The proper escape sequence would be something along the lines of

wchar_t * str = L"\x0627";

See this question: character constant:\000 \xhh

Edit: Oh, sorry, I missed the iPhone and Objective-C tags. The above is valid for generic C/C++, but I have not worked with iPhone development so your mileage may vary.




回答5:


\ is the escape character in objective c, use it before the letter to be escaped like :

NSString temp = @" hello \"temporary.h\" has been inported";

Here if you print the temp string in textview or logs, you will see " being printed as well because we have used the \ before them which is the escape character



来源:https://stackoverflow.com/questions/833822/how-do-i-escape-a-unicode-character-in-my-objective-c-source-code

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