objective-c - char/NSData/NSString
3987 ワード
基礎知識
NSString & NSData & char
Definition
Coding
char
毎に印刷する場合、中国語の文字化けしは一度に2つ印刷できないため、後のunicode
部分に解決方法があります. const char *chars = "this is a string, and contain ";
// char to NSString
NSString *string = [[NSString alloc] initWithCString:chars encoding:NSUTF8StringEncoding];
NSLog(@"%lu, %@", string.length, string); // 32, this is a string, and contain
// NSString to char
chars = [string cStringUsingEncoding:NSUTF8StringEncoding];
NSLog(@"%lu, %s", strlen(chars), chars); // 36, this is a string, and contain 中文
NSData *dataWithBytes = [NSData dataWithBytes:chars length:strlen(chars)];
NSLog(@"%@", dataWithBytes);
// <74686973 20697320 61204320 73747269 6e672c20 616e6420 636f6e74 61696e20 e4b8ade6 9687>
NSString *string = @"this is a string, and contain ";
// NSString to data
NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
NSLog(@"%@", data); // <74686973 20697320 61207374 72696e67 2c20616e 6420636f 6e746169 6e20e4b8 ade69687>
// NSData to NSString
string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"%@", string); // this is a string, and contain
// NSString to int ASCII
NSString *charString = @"A";
int asciiCode = [charString characterAtIndex:0];
NSLog(@"%i", asciiCode); // 65
// int to NSString
asciiCode = 66;
charString = [NSString stringWithFormat:@"%c", asciiCode];
NSLog(@"%@", charString); // B
// char to int ASCII
char character = 'A';
int asciiCode = (int)character;
NSLog(@"%i", asciiCode); // 65
// int to char
asciiCode = 66;
character = (char)asciiCode;
NSLog(@"%c", character); // B
unicode
NSString *theString = @"g";
unichar theChar = [theString characterAtIndex:0];
NSString *theString1 = [NSString stringWithFormat:@"%c", theChar];
NSString *theString2 = [NSString stringWithFormat:@"%C", theChar];
NSLog(@"%@, %d, %@, %@",theString, theChar, theString1, theString2);
// g, 103, g, g
theString = @" ";
theChar = [theString characterAtIndex:0];
theString1 = [NSString stringWithFormat:@"%c", theChar];
theString2 = [NSString stringWithFormat:@"%C", theChar];
NSLog(@"%@, %d, %@, %@",theString, theChar, theString1, theString2);
// , 23478, ¶,