#import <Foundation/Foundation.h>
void test(){
NSString *str = @"http://www.itheima.com";
//截取
NSString *strSub = [str substringFromIndex:10];
NSLog(@"strSub = %@",strSub);
NSString *strSub1 = [str substringToIndex:4];
NSLog(@"strSub1 = %@",strSub1);
// NSRange r1 = {2,7}; r1
NSString *strSub2 = [str substringWithRange:NSMakeRange(2, 7)];
NSLog(@"strSub2 = %@",strSub2);
}
int main(int argc, const char * argv[]) {
@autoreleasepool {
NSString *str = @"<itcast>传智播客X好</itcast>";
//1,找到@">"首次出现的位置,+1 得到要截取的起始位置
NSRange r1 = [str rangeOfString:@">"];
NSUInteger loc1 = r1.location + 1;
//2,找到 @"</"的位置-loc1,得到要截取的内容的长度
NSUInteger len = [str rangeOfString:@"</"].location - loc1;
//3,使用loc1和Len 构建一个新的range,然后截取这个range的字符串
NSRange r2 = {loc1,len};
//4,使用substringWithRange 截取一个范围
NSString *subStr = [str substringWithRange:r2];
NSLog(@"subStr = %@",subStr);
NSString *strNew = [str stringByReplacingOccurrencesOfString:@"传智播客X好" withString:@"艾水水"];
NSLog(@"strNew = %@",strNew);
}
return 0;
} |
|