文字列分割と結合


文字列を、特定の文字(デリミタ)で分割したい場合はNSStringのcomponentsSeparatedByStringが便利。結果はNSArrayで返されます。

ソースコード

NSString *time = @"12:30:43";
NSArray *timeParts = [time componentsSeparatedByString:@":"];
NSLog(@"%@", timeParts);

実行結果

2012-02-15 15:59:26.158 SplitStrings[4603:f803] (
    12,
    30,
    43
)

NSArray(もしくはNSMutableArray)などに入っている文字列を、1つの文字列に結合したい場合は、NSArrayのcomponentsJoinedByStringが便利です。

ソースコード

NSString *time = @"12:30:43";
NSArray *timeParts = [time componentsSeparatedByString:@":"];
NSLog(@"%@", [timeParts componentsJoinedByString:@"*"]);

実行結果

2012-02-15 16:31:48.983 Numbers[4914:f803] 12*30*43

[timeParts3 componentsJoinedByString:@”:”];

Comments

comments

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です