How do I create an NSString containing an NSLineSeparatorCharacter?

十年热恋 提交于 2019-12-13 15:09:17

问题


NSString is pretty unicode friendly. So normally when I want to create a string containing unicode, I can pop it directly into a string literal like so:

NSString *myString = @"Press ⌘Q to quit…";

But that doesn't work with using a line separator (AKA: 
NSLineSeparatorCharacter, Unicode U+2028, UTF-8 E2 80 A8). The compiler (correctly) interprets this as a line break, which is a no-no in C syntax.

-stringWithFormat: doesn't help either. Trying

NSString *myString = [NSString stringWithFormat@"This is%don two lines…", NSLineSeparatorCharacter];

gives me the string "This is8232on two lines…".


回答1:


Turns out -stringWithFormat: is the right way to go. I just need to use %C as the substitution instead of %d. NSLineSeparatorCharacter is an enumeration (and thus, integral), so the compiler thinks %d is what I should be using. But %C is Cocoa's way of inserting unichar types. With a little casting...

NSLog(@"This is%Con two lines…", (unichar)NSLineSeparatorCharacter);

Works like a charm!

Also note Ken's comment below: you can embed the character directly in a string literal using an escape sequence:

@"This is\u2028on two lines…"


来源:https://stackoverflow.com/questions/11384857/how-do-i-create-an-nsstring-containing-an-nslineseparatorcharacter

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