1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

NSString/NSMutableString関連のメモ

Last updated at Posted at 2014-01-06
NSString
    // 文字列の連結.
    NSString *str1 = @"文字列1";
    NSString *str2 = @"文字列2";
    NSString *str3 = [str1 stringByAppendingString:str2];
    NSLog(@"str1[%@] str2[%@] str3[%@]", str1, str2, str3);
    
    // 文字数の取得(lengthはメソッドだけどプロパティのように書ける).
    NSLog(@"str1[%d] str2[%d] str3[%d]", [str1 length], str2.length, str3.length);
    
    // 文字列の一部を取り出す.
    NSLog(@"%@", [str3 substringFromIndex:4]);
    NSLog(@"%@", [str3 substringToIndex:4]);
    NSLog(@"%@", [str3 substringWithRange:NSMakeRange(2, 4)]);
    
    // 文字列の検索.
    NSString *target = @"1";
    NSRange range = [str3 rangeOfString:target];
    if (range.location == NSNotFound) {
        NSLog(@"%@は見つかりませんでした", target);
    }
    else {
        NSLog(@"%@は%d文字目にありました", target, range.location+1);
    }
    
    // 文字列の比較.
    if ([str1 isEqualToString:str2]) {
//    if ([[str1 lowercaseString] isEqualToString:[str2 lowercaseString]]) {
        NSLog(@"同じです");
    }
    else {
        NSLog(@"違います");
    }
    
    // 文字列の置換.
    range = NSMakeRange(2, 4);
    NSString *rep = [str3 stringByReplacingCharactersInRange:range withString:@"あいうえお"];
    NSLog(@"[%@]=>[%@]", str3, rep);
    rep = [str3 stringByReplacingOccurrencesOfString:@"列" withString:@"数"];
    NSLog(@"[%@]=>[%@]", str3, rep);
    
    // 文字列を数値やBOOL値に変換.
    NSString *strNum = @"123456789";
    NSLog(@"%d", [strNum integerValue]);
    NSString *y = @"y";
    NSString *T = @"T";
    NSLog(@"y[%@] strNum[%@] T[%@]", ([y boolValue]?@"YES":@"NO"), ([strNum boolValue]?@"YES":@"NO"), ([T boolValue]?@"YES":@"NO"));
    
    // 編集可能な文字列.
    NSMutableString *mstr = [NSMutableString stringWithCapacity:8];
    NSLog(@"%@ len[%d]", mstr, mstr.length);
    [mstr appendString:@"12345"];
    NSLog(@"%@ len[%d]", mstr, mstr.length);
    [mstr appendString:@"67890"];
    NSLog(@"%@ len[%d]", mstr, mstr.length);
    mstr = [NSMutableString string];
    NSLog(@"%@ len[%d]", mstr, mstr.length);
    [mstr setString:@"ABCDEFGHIJKLMNOPQRSTUVWXYZ"];
    NSLog(@"%@ len[%d]", mstr, mstr.length);
    [mstr deleteCharactersInRange:NSMakeRange(5, 3)];
    NSLog(@"%@ len[%d]", mstr, mstr.length);
    [mstr insertString:@"fgh" atIndex:5];
    NSLog(@"%@ len[%d]", mstr, mstr.length);
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?