1.字符串的截取
字符串的截取用: 字符串 +substring..
如果开始就截取用from, 如果截取到用to。
截取的范围先rande{从哪,长度}
- 从索引开始截取
NSString *str = [@"123456" substringFromIndex:3];
str = @"456";
- 截取到索引
NSString *str = [@"123456" substringFromIndex:4];
str = @"1234";
- 截取的范围,长度
NSRange r={2,3};//截取的范围,长度
NSString *str =[@"123456" substringWithRange:r];
str8= @"345";
2.字符串的拼接
NSString *str =[NSString stringWithFormat:@"%@%@",str1,str2];
NSString *str = [str1 stringByAppendingString:str2];(比较好一点)
NSString *str = [str stringByAppendingFormat:@"%@,%@",string1, string2]
3.字符串的比较
- 比较两个字符串是不是同一个东西
NSString *str01 =[NSString stringWithFormat:@"iphone"];
NSString *str02 =[NSString stringWithFormat:@"ipad"];
NSLog(@"str01的地址%p",str01); 0x656e6f68706965
NSLog(@"str02的地址%p",str02); 0x6461706945
- 判断地址是否相同用==判断(双等号)
if (str01==str02){
NSLog(@"他俩是同一个字符串");
}else{
NSLog(@"他俩不是同一个字符串");
}
- 判断字符串的内容是否相同
if ([str01 isEqualToString:str02]) {
NSLog(@"他俩内容相同");
}else{
NSLog(@"他俩内容不相同");
}
- 字符串的大小比较
NSComparisonResult CR =[str01 compare:str02];
if (CR==NSOrderedAscending) {
NSLog(@"str02>str01");
}else if (CR == NSOrderedSame){
NSLog(@"str02=str01");
} else{
NSLog(@"str02<str01");
}
结果 str02<str01
4.字符串大小写转换
NSString *str11 =@"Hello wORld";
- 改写成全部大写
NSString *ustr=[str11 uppercaseString];
结果 HELLO WORLD
- 改写成全部小写
NSString *ustr=[str11 lowercaseString];
结果 hello world
- 改写成首字母大写
NSString *ustr=[str11 capitalizedString];
结果 Hello World
5.判断字符串的开始和结束
NSString *str12 =@"ios-iphone";
- 开始
if ([str12 hasPrefix:@"io"]) {
NSLog(@"YES");
}else{
NSLog(@"NO");
}
- 结束
if ([str12 hasSuffix:@"io"]) {
NSLog(@"YES");
}else{
NSLog(@"NO");
}
6.字符串的替换
NSString *str =@"qwertyuiop";
NSString *str=[str stringByReplacingOccurrencesOfString:str withString:@"tyuio"];
str=tyuio
NSString *str15 =[str stringByReplacingCharactersInRange:NSMakeRange(4,5) withString:@"A"];
str15=qwerAp
7.可变字符串
NSMutableString继承与NSString
NSMutableString *mstr = [NSMutableString stringWithFormat:@"iphone"];
- 插入字符串
[mstr insertString:@"ipad" atIndex:3];
mstr =iphipadone
-追加字符串
mstr =iphoneipad
[mstr appendString:@"ipad"];
mstr =iphoneipadipad
-给定一个图片文件名,判断字符串中是否以“png”结尾,如果是就替换成“jpg”,如果 不是,就拼接”.jpg
NSMutableString *str0=[NSMutableString stringWithFormat:@"001.png"];
if ([str0 hasSuffix:@"001.png"]){
//求字符串长度的方法 length
[str0 replaceCharactersInRange:NSMakeRange(str0.length-3, 3) withString:@"jpg"];
}else {
[str0 appendString:@".jpg"];
}
str0=001.jpg