oc基础 不可变字符串的创建和使用
简介:下面都是字符串基本用法。
1.字符串的创建
//创建oc常量字符串
NSString *str=@"hello world!";
NSLog(@"%@",str); //用c语言的字符串来创建oc的字符串
char *ch="hello world C";
NSString *str2=[[NSString alloc] initWithUTF8String:ch];
NSLog(@"%@",str2); //用格式化来创建字符串
int a=;
NSString *str3=[[NSString alloc] initWithFormat:@"%@ %d",str2,a];
NSLog(@"%@",str3); //用类方法来创建字符串
NSString *str4=[NSString stringWithFormat:@"%@%@",str2,str];
NSString *str5=[NSString stringWithUTF8String:ch];
NSLog(@"%@ , %@",str4,str5); //读取文件来创建字符串
NSString *path=@"/Users/qf/Desktop/my2/Car.h";
NSError *error;
NSString *str6=[[NSString alloc] initWithContentsOfFile:path encoding:NSUTF8StringEncoding error:&error];
NSLog(@"%@",str6);
2.字符串的使用
(1)判断两个字符串是否相等和比较大小(区分大小写)
NSString *str1=@"hello world";
NSString *str2=@"Hello world"; if([str1 isEqualToString:str2])
{
NSLog(@"yes");
}
else
{
NSLog(@"no");
}
if ([str1 compare:str2]==-) {
NSLog(@"str1<str2");
}
else if ([str1 compare:str2]==)
{
NSLog(@"str1==str2");
}
else
{
NSLog(@"str1>str2");
}
(2)判断比较大小(不区分大小写)
//不区分大小写
if ([str1 caseInsensitiveCompare:str2]==-) {
NSLog(@"str1<str2"); }
else if ([str1 caseInsensitiveCompare:str2]==)
{
NSLog(@"str1==str2"); }
else
{
NSLog(@"str1>str2"); }
(3)大小写转换
//转大写
NSString *str3=[str1 uppercaseString];
NSLog(@"%@",str3); //转小写
NSString *str4=[str2 lowercaseString];
NSLog(@"%@",str4); //首字母大写,其他变小写
NSString *str5=[str2 capitalizedString];
NSLog(@"%@",str5);
(4)搜索字符
//查找是否包含
NSString *str6=@"I love huang xiao dan.";
NSString *str7=@"love";
NSRange range=[str6 rangeOfString:str7];
NSLog(@"%d,%d",range.location,range.length);
if (range.location==NSNotFound) {
NSLog(@"没找到");
}
else
{
NSLog(@"找到了");
} //查找某个位置的字符
char c=[str6 characterAtIndex:];
NSLog(@"%c",c);
(5)字符截取
//从位置0开始,截取到指定的位置,开区间
NSString *str8=[ str6 substringToIndex:];
NSLog(@"%@",str8); //从指定的位置开始,一直截取到字符串的末尾,闭区间
NSString *str9=[str6 substringFromIndex:];
NSLog(@"%@",str9); //截取指定范围的字符串
NSRange range1=NSMakeRange(, );
NSString *str10=[str6 substringWithRange:range1];
NSLog(@"%@",str10);
(6)判断以字符串开头或结尾
//判断字符串是否以“I”开头
if([str6 hasPrefix:@"I"])
{
NSLog(@"yes");
}
else
{
NSLog(@"no");
}
//判断字符串是否以“dan”结尾
if([str6 hasSuffix:@"dan"])
{
NSLog(@"yes");
}
else
{
NSLog(@"no");
}
(7)字符串转数字类型
NSString *str11=@""; NSLog(@"%d",[str11 intValue]);
//转其他数字类型类似
(8)字符串替换
NSString *str12=@"I am a good student.";
NSString *str13=[str12 stringByReplacingCharactersInRange:NSMakeRange(, ) withString:@"asjhja"];
NSLog(@"%@",str13);
(9)字符串的分割和组合
//单个字符分割
NSArray *array=[str12 componentsSeparatedByString:@" "];
NSLog(@"%@",array); //字符集进行分割
NSString *str14=@"I like a cat,and!dn sa!";
NSCharacterSet *set=[NSCharacterSet characterSetWithCharactersInString:@" , !"];
NSArray *array2=[str14 componentsSeparatedByCharactersInSet:set];
NSLog(@"%@",array2); //字符组合
NSString *str15=[array2 componentsJoinedByString:@"!"];
NSLog(@"%@",str15);