NSString NSMutableString objective-c中字符串操作

 // 1.NSString 不可变字符串

        // 使用字面量创建字符串对象
        NSString *str1 = @"字符串1";

        // 使用初始化方法创建
        NSString *str2 = [[NSString alloc] initWithFormat:@"age = 18"]; // 不用占位符
        NSLog(@"%@",str2);

        NSInteger a = 10, b = 20;
        NSString *res = [[NSString alloc] initWithFormat:@"%ld", a + b]; // 用占位符
        NSLog(@"res = %@", res);

        // 使用便利构造器创建字符串对象
        NSString *str4 = [NSString stringWithFormat:@"字符串4"];   // 对应初始化方法
        NSLog(@"%@", str4);


        // 获取字符串长度
        NSUInteger l = [str4 length];  // 给字符串对象发送length消息,可以获取到字符串长度
        NSLog(@"length = %ld", l);

        // 判断后缀 区分大小写
        NSString *str5 = @"icon.png";
        BOOL b1 = [str5 hasPrefix:@"ic"]; // 没有分割,写多少字符都可以
        NSLog(@"%d", b1);


        // 比较字符串相同
        BOOL b2 = [str5 isEqualTo:@"icon.png"];
        NSLog(@"%d", b2);


        // 截取字符串 NSRange
        NSString *str6 = [str5 substringWithRange:NSMakeRange(4, 4)];
        NSLog(@"%@", str6);


        // 拼接字符串
        NSString *name = @"小泽";
        NSString *newStr = [name stringByAppendingString:@"老师"];
        NSLog(@"%@", newStr);


        // 替换字符串
        NSString *str8_1 = [newStr stringByReplacingOccurrencesOfString:@"老师" withString:@"菇凉"];
        NSLog(@"str8_1 = %@", str8_1);

        NSString *str8_2 = [newStr stringByReplacingCharactersInRange:NSMakeRange(2, 2) withString:@"菇凉你好"];
        NSLog(@"str8_2 = %@", str8_2);


        // 比较字符串
        NSString *str9 = @"abc";
        NSString *str10 = @"abcd";

        NSComparisonResult res1 = [str9 compare:str10];
        NSLog(@"res1 = %ld", res1);


        // 字符串和数值类型的转换
        NSString *str11 = @"123.4";
        NSLog(@"%.2f", [str11 doubleValue]);


        // 大小写转换
        NSString *str7 = @"Zhao YA dong";
        NSLog(@"%@", [str7 lowercaseString]);
        NSLog(@"%@", [str7 uppercaseString]);
        NSLog(@"%@", [str7 capitalizedString]);




        // 可变字符串
        NSMutableString *mutableStr1 = [[NSMutableString alloc] initWithFormat:@"abc"];
        NSLog(@"%@", mutableStr1);

        // 拼接
        [mutableStr1 appendFormat:@"def"];
        [mutableStr1 appendString:@"gh"];
        NSLog(@"%@", mutableStr1);

        // 删除
        [mutableStr1 deleteCharactersInRange:NSMakeRange(2, 1)];
        NSLog(@"%@", mutableStr1);

        // 插入
        [mutableStr1 insertString:@"cc" atIndex:2];
        NSLog(@"%@", mutableStr1);

        // 修改
        [mutableStr1 replaceCharactersInRange:NSMakeRange(0, 2) withString:@"yadong"];
        NSLog(@"%@", mutableStr1);

你可能感兴趣的:(操作,objective)