OC 字符串

 unichar data[6] = {97,98,99,100,101,102};

        //使用Unicode数值数组初始化字符串

        NSString* str = [[NSString alloc]initWithCharacters:data length:6];

        NSLog(@"%@",str);

        //将C风格的字符串转换成NSString对象

        char* cstr = "Hello,iOS!";

        NSString* str2 = [NSString stringWithUTF8String:cstr];

        NSLog(@"%@",str2);

        //将字符串写入指定文件

        [str2 writeToFile:@"myFile.txt" atomically:YES encoding:NSUTF8StringEncoding error:nil];

        //读取文件内容,用文件内容初始化字符串

        NSString* str3 = [NSString stringWithContentsOfFile:@"myFile.txt" encoding:NSUTF8StringEncoding error:nil];

        NSLog(@"%@",str3);

        

        NSString* str4 = @"hello";

        NSString* str5 = @" word";

        //在str后追加固定的字符串

        str4 = [str4 stringByAppendingString:str5];

        NSLog(@"%@",str4);

        const char*conStr= [str4 UTF8String];

        NSLog(@"获取C字符串对于的C风格字符串:%s",conStr);

        NSLog(@"str按UTF-8字符集解码后字节数为:%lu",[str4 lengthOfBytesUsingEncoding:NSUTF8StringEncoding]);

        NSLog(@"获取str的前10个字符组成的字符串:%@",[str4 substringToIndex:10]);

        NSLog(@"获取str从第5个字符开始,到后面组成的字符串:%@",[str4 substringFromIndex:5]);

        //[str substringWithRange:NSMakeRange(5,3)]从第5个开始,截取3个长度

        NSLog(@"获取从第5个字符到第10个字符的字符串:%@",[str4 substringWithRange:NSMakeRange(5,3)]);

        //获取hello在字符中的位置

        NSRange range = [str4 rangeOfString:@"hello"];

        NSLog(@"获取hello在字符中的位置:%ld,长度:%ld",range.location,range. length);

        //将str字符转换成大写

        str4 = [str4 uppercaseString];

        NSLog(@"%@",str4);


===============================================

 NSString* str = @" word";

        NSMutableString* MTStr = [NSMutableString stringWithFormat:@"Hello"];

        //追加固定字符串

        [MTStr appendString:str];

        NSLog(@"%@",MTStr);

        //追加带变量的字符串

        [MTStr appendFormat:@"%@",@"呵呵呵"];

         NSLog(@"%@",MTStr);

        //在指定的位置追加字符串

        [MTStr insertString:@"OOO" atIndex:5];

         NSLog(@"%@",MTStr);

        //删除位置5到位置8的所有字符串

        [MTStr deleteCharactersInRange:NSMakeRange(5, 3)];

         NSLog(@"%@",MTStr);

        //将“呵呵呵”替换成“!!!”

        [MTStr replaceCharactersInRange:NSMakeRange(10, 3) withString:@"!!!"];

         NSLog(@"%@",MTStr);


猜你喜欢

转载自blog.csdn.net/luochenlong/article/details/78802904