字符串
一.不可变字典:
1.字符串格式化处理
int age = 20;
NSString *name = @"陈真";
NSString *info = [NSString stringWithFormat:@"%@今年%d",name,age];
NSLog(@"%@",info);
2.截取字典
a.从哪个位置开始截取字符串(substringFromIndex)
例:NSString *newstring = [info substringFromIndex:2];
NSLog(@"%@",newstring);
NSString *str= @"床前明月光,疑是地上霜,。。。。";
NSString *ts = [str substringFromIndex:12];
NSLog(@"%@",ts);
b.截取字符串到哪个位置(substringToIndex)
例:
NSString *strr = [st substringToIndex:5];
NSString *strr1 = [st substringToIndex:12]; NSLog(@"%@ %@“,strr,strr1)
3截取字符串-从哪里来 到哪里去,,这种方法就是多了一个结构体,NSrage是一个结构体。(substringWithRange
例:NSRange rage;
结构体所在位置
rage.location=6;
结构体的长度
rage.length=5;
NSLog(@"%@",[st substringWithRange:rage]);
3.把字符串通过指定字符 分割成数组(componentsSeparatedByString)
NSArray *message = [st componentsSeparatedByString:@","];
NSLog(@"%@",message[2]);
for (id k in message){
NSLog(@"%@",k);
}
4.字符的大小写转换(uppercaseString,lowercaseString,capitalizedString) 英文转成大写
NSString *english = @"chenhong";
NSLog(@"%@",english.uppercaseString );
转成小写
NSString *xiaoxie = @"CHENHONG";
NSLog(@"%@",xiaoxie.lowercaseString);
首字母大写
NSLog(@“%@“,english.capitalizedString);
5拼接字符串有三种(stringWithformat,stringByAppendingString),(stringByAppendingFormat)
1.stringWithformat
2.stringByAppendingString
NSString *ss = @"我是";
NSString *tt = @"中国人";
NSString *t= [ss stringByAppendingString:tt];
NSLog(@"%@",t);
3.(stringByAppendingFormat)
NSString *y = [ss stringByAppendingFormat:@"%@而且还是贵州人",tt];
NSLog(@“%@",y);
##:1.不可变字符串拼接:是在原来字符串的上拼接一个字符串,生产一个新的字符串;原来的字符串不改变。
2.可变字符串拼接:原来的字符串又添加了一个字符串 与原来的字符串 合成一个字符串(还是原来字符串的对象)(appendFormat,appendString)
5.查询字符串
判断字符串是否包含某一个字符串
NSString *x = @"我爱东方不败,令狐冲才是";
NSRange z = [x rangeOfString:@"令狐冲"];
NSLog(@"%ld",NSNotFound);
if(z.location !=NSNotFound)
NSLog(@"%@",x);
else
NSLog(@"骗人!!!");
以什么开始(字符串的头部包含什么内容)
BOOL result = [x hasPrefix:@"1"];
if (result)
NSLog(@"正确");
else
NSLog(@"错误");
以什么结束(字符串的尾部部包含什么内容)
if ([x hasSuffix:@"党"]) {
NSLog(@"正确");
}
else
NSLog(@"错误");
二.可变字典
1.把指定字符串替换成另一个字符串(replaceCharactersInRange)
NSMutableString *name = [[NSMutableString alloc]initWithString:@"batg"];
NSRange rang;
rang100.location =1;
rang100.length = 3;
[name replaceCharactersInRange:rang withString:@"ter"];
NSLog(@"%@",name1);
2.删除指定位置长度的字符串(deleteCharactersInRange)
[name deleteCharactersInRange:rang];
3.字符串比较
两种方法:
1.compare
NSString *aa [email protected]"hong";
NSString *bb = @"ABC";
NSComparisonResult result1 =[aa compare:bb];
if (result1 == NSOrderedSame) {
NSLog(@"aa<bb");
}
else
NSLog(@"aa>bb");
2.caseInsensitiveCompare
NSString *cc [email protected]"hongw";
NSString *dd = @"ABCd";
NSComparisonResult result2 =[cc compare:dd];
if (result2 == NSOrderedDescending) {
NSLog(@"aa>bb");
}