Вопрос

I'm trying to get a specific number of heart characters at runtime, using this code:

NSString *glyph = @"❤︎";
NSString *padded = [@"" stringByPaddingToLength:4 withString:glyph startingAtIndex:0];
NSLog(@"glyph=%@, padded=%@", glyph, padded);

which produces this output:

2014-01-26 20:04:57.962 Machismo[31073:70b] glyph=❤︎, padded=❤︎❤︎

All other characters besides heart(❤︎) that I've tried, do produce expected results (a string of four hearts in this case). I can use other techniques to get the output I want, but this method produces very strange results. For example, if I request a three-character string and display the result as a button label, I see two hearts, one black and one red(!)

What could possibly be going on here?

Это было полезно?

Решение

The glyph character(❤︎) you have used is consists of two unicode characters(\u2764\ufe0e), so the two hearts displaying in (padded=❤︎❤︎) are correct and represents four characters for padding length 4.

Other simple characters like "k" consists of one unicode character so it appears four times with padding length 4.

This heart character(❤) consists of one unicode character(\u2764), so if you use this, then four hearts will be displayed with padding length 4.

You can also code like:

NSString *glyph = @"\u2764"; //for NSString *glyph = @"❤";

NSString *glyph = @"\u2764\ufe0e"; //for NSString *glyph = @"❤︎";

UPDATE after comments: Not sure about the easy way but I use following code for special characters to view its unicode :

NSData *data = [@"❤︎" dataUsingEncoding:NSNonLossyASCIIStringEncoding];
NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; NSLog(@"%@", str);
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top