NSString
1.初始化
-
char *str1="C string";//这是C语言创建的字符串 -
NSString *str2=@"OC string";//ObjC字符串需要加@,并且这种方式创建的对象不需要自己释 放内存 -
//下面的创建方法都应该释放内存 -
NSString *str3=[[NSString alloc] init]; -
str3=@"OC string"; -
-
NSString *str4=[[NSString alloc] initWithString:@"Objective-C string"]; -
-
NSString *str5=[[NSString alloc] initWithFormat:@"age is %i,name is%.2f",19,1.72f]; -
-
NSString *str6=[[NSString alloc] initWithUTF8String:"C string"];//C语言的字符串转换为ObjC字符串 -
-
//以上方法都有对应静态方法(一般以string开头),不需要管理内存(系统静态方法一般都是自动 释放) -
NSString *str7=[NSString stringWithString:@"Objective-C string"];
2.字符串的大小写和比较
-
NSLog(@""Hello world!" to upper is %@",[@"Hello world!" uppercaseString]); //结果:"Hello world!" to upper is HELLO WORLD! -
-
NSLog(@""Hello world!" to lowwer is %@",[@"Hello world!" lowercaseString]); //结果:"Hello world!" to lowwer is hello world! -
-
//首字母大写,其他字母小写 -
NSLog(@""Hello world!" to capitalize is %@",[@"Hello world!" capitalizedString]); -
//结果:"Hello world!" to capitalize is Hello World! -
-
BOOL result= [@"abc" isEqualToString:@"aBc"]; -
NSLog(@"%i",result); -
//结果:0 -
-
NSComparisonResult result2= [@"abc" compare:@"aBc"];//如果是[@"abc"caseInsensitiveCompare:@"aBc"]则忽略大小写比较 -
if(result2==NSOrderedAscending){//-1实际上是枚举值 -
NSLog(@"left<right."); -
}else if(result2==NSOrderedDescending){//1 -
NSLog(@"left>right."); -
}else if(result2==NSOrderedSame){//0 -
NSLog(@"left=right."); } -
//结果:left>right. -
}
3.截取和匹配
NSLog(@"has prefix ab? %i",[@"abcdef" hasPrefix:@"ab"]);//结果:has prefix ab? 1 YES 头部匹配 NSLog(@"has suffix ab? %i",[@"abcdef" hasSuffix:@"ef"]);//结果:has suffix ab? 1 NO 尾巴匹配 NSRange range=[@"abcdefabcdef" rangeOfString:@"cde"];//注意如果遇到cde则不再往后面搜索,如果从后面搜索或其他搜索方式可以设置第二个options参数if(range.location==NSNotFound){ NSLog(@"not found.");}else{ NSLog(@"range is %@",NSStringFromRange(range));}//结果:range is {2, 3}4.字符串的分割
NSLog(@"%@",[@"abcdef" substringFromIndex:3]);//结果:def //从index=3开始直到末尾,包含index=3 NSLog(@"%@",[@"abcdef" substringToIndex:3]);//结果:abc //从index=0开始直到index=3,但是不包含index=3 NSLog(@"%@",[@"abcdef" substringWithRange:NSMakeRange(2, 3)]);//结果:cde NSString *str1=@"12.abcd.3a";NSArray *array1=[str1 componentsSeparatedByString:@"."];//字符串分割NSLog(@"%@",array1);
//
(
12,
abcd,
3a
)
5.其他
NSLog(@"%i",[@"12" intValue]);//类型转换//结果:12 NSLog(@"%zi",[@"hello world,世界你好!" length]);//字符串长度注意不是字节数//结果:17 NSLog(@"%c",[@"abc" characterAtIndex:0]);//取出制定位置的字符//结果:a const char *s=[@"abc" UTF8String];//转换为C语言字符串NSLog(@"%s",s);//结果:abc

浙公网安备 33010602011771号