Objective-c的FoundObjective-c的Foundation中常用类2——NSString和NSMutableStringation中常用类2——NSString和NSMutableStri
继续NSString,由于用的多,所以应该重点掌握
1、求字符串长度
[cpp]
NSString *myName = @"AOBAMA";
int length = (int)[myName length];//发现返回值类型是NSUInteger,不强转有警告,自己也不知道强转是不是常用的方法,望看到的网友能告知一下
NSLog(@"字符串的长度是:%d",length);
if ([myName length] > 5) {
NSLog(@"AAAAA");//打印AAAAA
}
2、字符串的相关转换
改变大小写
[cpp]
NSString *string = @"Where are You,Boy!";
//都大写
NSLog(@"%@",[string uppercaseString]);//打印WHERE ARE YOU,BOY!
//都小写
NSLog(@"%@",[string lowercaseString]);//打印where are you,boy!
//所有单词首字母大写,其它字母小写
NSLog(@"%@",[string capitalizedString]);//打印Where Are You,Boy!
将字符串转化成基本数据类型
[cpp]
NSString *aboutFloat = @"3.14";
NSString *aboutBool = @"NO";
NSLog(@"%f",[aboutFloat floatValue]);//打印3.140000
NSLog(@"%d",[aboutBool boolValue]);//打印0
//把float型转化为整型
NSLog(@"%d",[aboutFloat intValue]);//打印3
把两个字符串合并成一个字符串
[cpp]
//方法一
NSString *str1 = @"Hello";
NSString *str2 = @" World";
NSString *str3 = [[NSString alloc]initWithFormat:@"%@%@",str1,str2];
NSLog(@"str1与str2合并成str3的结果为:%@",str3);//打印结果:str1与str2合并成str3的结果为:Hello World
//方法二
NSString *str4 = [str1 stringByAppendingString:str2];
NSLog(@"str1与str2合并成str4的结果为:%@",str4);//打印结果:str1与str2合并成str4的结果为:Hello World
//连接多个字符串
NSString *str5 = [str1 stringByAppendingFormat:@"%@%@%@",str1,str2,str3];
NSLog(@"str5为:%@",str5);//打印结果:str5为:HelloHello WorldHello World
3、是否以一个字符串开头hasPrefix:,是否以一个字符串结尾hasSuffix
[cpp]
NSString *str6 = @"who are you";
BOOL isStart1 = [str6 hasPrefix:@"wh"];
BOOL isStart2 = [str6 hasPrefix:@"h"];
BOOL isEnd1 = [str6 hasSuffix:@"u"];
BOOL isEnd2 = [str6 hasSuffix:@"o"];
NSLog(@"结果:%d,,,%d,,,%d,,,%d",isStart1,isStart2,isEnd1,isEnd2);//结果:1,,,0,,,1,,,0
4、将字符串按规则截取成数组
[cpp]
NSString *str7 = @"you/have/a/baby";
NSArray *array = [str7 componentsSeparatedByString:@"/"];
NSLog(@"%@",array);//数组可以直接打印不用遍历
/*打印结果
(
you,
have,
a,
baby
)
*/
5、字符串的截取
[cpp]
NSString *str8 = [str7 substringFromIndex:2];//从第二个位置开始街区包括2,当然以0开头
NSLog(@"%@",str8);// u/have/a/baby
NSString *str9 = [str7 substringToIndex:5];//从开始到规定的位置,但不包括该位置
NSLog(@"%@",str9);// you/h
//根据范围截取
NSRange range = NSMakeRange(2, 3);//先定义范围,也可以这样定义NSRange range = {2,3};
NSLog(@"location..%ld length...%ld",range.location,range.length);// location..2 length...3
range.location = 3;//包括2
range.length =4;//从2开始长度为3的子字符串
NSLog(@"location..%ld length...%ld",range.location,range.length);// location..3 length...4
NSString *str10 = [str7 substringWithRange:range];
NSLog(@"%@",str10);// /hav
6、字符串查询
[cpp] www.zzzyk.com
NSRange range2 = [str7 rangeOfString:@"have"];
NSRange range3 = [str7 rangeOfString:@"aaa"];
NSLog(@"location1...%ld",range2.location);
NSLog(@"location2...%ld",range3.location);
打印结果:
location1...4
location2...9223372036854775807
我们可以根据要查询的字符串在源字符串中的位置来判断查找结果。
NSMutableString的相关用法
补充:软件开发 , C++ ,