- int main(int argc, const char * argv[])
- {
- @autoreleasepool {
-
- //----------------NSString-----------------------------
- NSString *str1 = @"这是一个字符串常量";
- NSLog(@"str1 = %@",str1);
- //创建一个空字符串
- NSString *str2 = [[NSString alloc]init];
- NSString *str3 = [NSString string];
- NSLog(@"str2 = %@",str2);
- NSLog(@"str3 = %@",str3);
- //快速创建一个字符串
- NSString *str4 = [[NSString alloc]initWithString:str1];
- NSString *str5 = [NSString stringWithString:str1];
- NSLog(@"str4 = %@",str4);
- NSLog(@"str5 = %@",str5);
- //创建一个格式化字符串
- NSString *str6 = [[NSString alloc]initWithFormat:@"%d",10];
- NSString *str7 = [NSString stringWithFormat:@"%.2f",10.8099887];
- NSLog(@"str6 = %@",str6);
- NSLog(@"str7 = %@",str7);
-
- //比较两个字符串内容是否相等
- if ([str6 isEqualToString:str7]) {
- NSLog(@"str6 is EqualToString str7");
- }else{
- NSLog(@"str6 is not EqualToString str7");
- }
-
- //转换为基本数据类型
- NSString *str8 = @"3";
- float f1 = [str8 floatValue];
- NSLog(@"str8 = %.2f",f1);
-
- //字符串拆分为数组
- NSString *str9 = @"命 运 就 算 颠 沛 流 离";
- NSArray *array = [str9 componentsSeparatedByString:@" "];
- NSLog(@"array = %@",array);
- NSLog(@"array[0] = %@",array[0]);
-
- //截取字符串
- NSString *str10 = @"123456789";
- NSString *subStr1 = [str10 substringToIndex:4];
- NSString *subStr2 = [str10 substringFromIndex:6];
- NSLog(@"subStr1 = %@",subStr1);
- NSLog(@"subStr2 = %@",subStr2);
-
- NSRange range = {4,2};
- NSString *subStr3 = [str10 substringWithRange:range];
- NSLog(@"subStr3 = %@",subStr3);
-
- //拼接字符串
- NSString *str11 = @"123";
- NSString *str12 = @"456";
- NSString *appStr1 = [[NSString alloc]initWithFormat:@"%@%@",str11,str12];
- NSString *appStr2 = [str11 stringByAppendingFormat:@"%@",str12];
- NSString *appStr3 = [str11 stringByAppendingString:str12];
- NSLog(@"appStr1 = %@",appStr1);
- NSLog(@"appStr2 = %@",appStr2);
- NSLog(@"appStr3 = %@",appStr3);
-
- //查找字符串
- NSString *str13 = @"qweradsfzxcvqazxsw";
- NSRange range1 = [str13 rangeOfString:@"dsfzx"];
- NSLog(@"%@",NSStringFromRange(range1));
- NSLog(@"%d",range1.location);
- if (range1.location != NSNotFound) {
- NSLog(@"str found");
- }else{
- NSLog(@"str not found");
- }
-
- /*------------NSMutableString 可变字符串-----------------*/
- //插入
- NSMutableString *mStr1 = [[NSMutableString alloc] initWithFormat:@"abcd"];
- [mStr1 insertString:@"defg" atIndex:4]; //注意:此处为在源字符串上修改,并未生成新的字符串
- NSLog(@"mStr1 = %@",mStr1);
-
- //替换
- [mStr1 replaceCharactersInRange:NSMakeRange(4, 4) withString:@"1234"];
- NSLog(@"%@",mStr1);
-
- //删除
- [mStr1 deleteCharactersInRange:NSMakeRange(4, 4)];
- NSLog(@"%@",mStr1);
- }
- return 0;
- }
复制代码
|
|