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

前端 未结 5 1678
北恋
北恋 2020-12-06 04:00

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 li

相关标签:
5条回答
  • 2020-12-06 04:18

    \ 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

    0 讨论(0)
  • 2020-12-06 04:28

    Example:

    NSString *stuff = @"The Greek letter Beta looks like this: \u03b2, and the emoji for books looks like this: \U0001F4DA";
    
    0 讨论(0)
  • 2020-12-06 04:31

    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.

    0 讨论(0)
  • 2020-12-06 04:39

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

    [string stringByAppendingFormat:@"%C", 0x2665];
    
    0 讨论(0)
  • 2020-12-06 04:40

    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.

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