以下の「String Format Specifiers」の要点部分を解説します。
String Format Specifiers
http://developer.apple.com/documentation/Cocoa/Conceptual/Strings/Articles/formatSpecifiers.html
こちらはC言語のprintf()関数の第一引数で使えるものと同様な指定子であり、 NSLog や NSString:stringWithFormat: などで使用できます。
フォーマット指定子 | 説明 |
---|---|
%@ | descriptionWithLocale: の戻り値。 descriptionWithLocale: が存在しない場合は description の戻り値 |
%% | %を使うとき |
%d,%D,%i | 符号付き32bit integer(long) |
%u,%U | 符号なし32bit integer(unsigned long) |
%hi | 符号付き16bit integer(short) |
%hu | 符号なし16bit integer(unsigned short) |
%qi,%lld | 符号付き64bit integer(long long) |
%qu,%llu | 符号なし64bit integer(unsigned long long) |
%x | 符号なし32bit integer(unsigned long)。16進表示。値は0〜9、a〜fが使われる |
%X | 符号なし32bit integer(unsigned long)。16進表示。値は0〜9、A〜Fが使われる |
%qx | 符号なし64bit integer(unsigned long long)。16進表示。値は0〜9、a〜fが使われる |
%qX | 符号なし64bit integer(unsigned long long)。16進表示。値は0〜9、A〜Fが使われる |
%o,%O | 符号なし32bit integer(unsigned long)。8進表示 |
%f | 64bit 浮動小数点数(double) |
%e | 64bit 浮動小数点数(double)。小文字のeを使った科学表記。例えば 10000.0 → 1.000000e+04 となる |
%E | 64bit 浮動小数点数(double)。大文字のEを使った科学表記。例えば 10000.0 → 1.000000E+04 となる |
%g | 64bit 浮動小数点数(double)。指数が0〜-4までは %f を指定したときと同様の表示、それ意外の値の場合は %e と同様。例えば 0.0001 → 0.0001、 0.00001 → 1e-05 となる |
%G | 64bit 浮動小数点数(double)。指数が0〜-4までは %f を指定したときと同様の表示、それ意外の値の場合は %E と同様。例えば 0.0001 → 0.0001、 0.00001 → 1E-05 となる |
%c | 8bit 符号なし。character(unsigned char) |
%C | 16bit 符号なし。Unicode character(unichar) |
%s | 末尾がNULLの 8bit unsigned character(char文字列) |
%S | 末尾がNULLの 16bit Unicode characters(ユニコード文字列) |
%p | Void pointer(void *)。アドレスの表示。16進表示。値は0〜9、A〜Fが使われる。頭に 0x が付く |
以下に使用例を記載します。
#import <Foundation/Foundation.h> int main (int argc, const char * argv[]) { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; //------------ char c_str[] = "abc"; NSLog(@"&c_str[0] = %p", &c_str[0]); // c_str[1] は c_str[0] のアドレスを+1したアドレスとなる。 NSLog(@"&c_str[1] = %p", &c_str[1]); NSLog(@"c_str = %s", c_str); // 「abc」と表示される。 unichar unic_str[6]; unic_str[0] = 0xF862; unic_str[1] = 0x6709; unic_str[2] = 0x9650; unic_str[3] = 0x4F1A; unic_str[4] = 0x793E; unic_str[5] = 0x00; NSLog(@"unic_str = %S", unic_str); // 「有限会社」と表示される(※出力された文字を選択すると分かりますがこれは1文字です)。 unic_str[0] = 0x0031; unic_str[1] = 0x20DE; unic_str[2] = 0x00; NSLog(@"unic_str = %S", unic_str); // 「□の中に1」と表示される。 NSString* ns_str = [NSString stringWithFormat:@"%S", unic_str]; NSLog(@"ns_str = %@", ns_str); // 「□の中に1」と表示される。 // ちなみに、この「□の中に1」をテキストエディタにコピペ、 // 保存した後にバイナリエディタで確認するとデータの並びは 31 E2 83 9E char c = 'a'; NSLog(@"c = %c", c); NSString* strB = @"テスト"; unichar uni_c = [strB characterAtIndex:0]; NSLog(@"uni_c(%%C) = %C", uni_c); // 「テ」」と表示される。 NSLog(@"uni_c(%%X) = %X", uni_c); // 「30C6」」と表示される。uni_c("テ")の16進表示。 NSLog(@"\\u30C6 = \u30C6"); // 「テ」と表示される。 NSLog(@"0x30C6 = %C", 0x30C6); // 「テ」と表示される。 //------------ [pool drain]; return 0; }