这几天学了字符串,数组,字典,集合还有类型转换的一些方法,学完之后能留在脑袋里的方法没几个😭,实在太难记。所以抽时间先来整理记忆一下有关字符串和类型转换的相关方法:
string --> NSString (不可变字符串) NSMultableString(可变字符串)
先总结这两种字符串共同的方法:
求字符串的长度 NSUInteger len = string.length;
获取字符串中的字符 unichar c = [string characterAtIndex:3]; 3这个位置是写下标
判断两个字符串是否相等 BOOL result = [string1 isEqualToString:string2];
字符串的比较 NSInteger comResult = [string1 compare:string2]; (0/1/-1)
从指定下标截取到最后 NSString *string = [string substringFromIndex:3];(包括该下标)
从头截取到给定下标 NSString *string = [string substringToIndex:6]; (不包括下标)
按照给定范围截取 NSRange range = {2, 4}; (从下标为2开始截取4个)
NSString *string = [string substringWithRange:range];
同上 NSString *string = [string substringWithRange:NSMakeRange(2, 4)];
字母大小写 (全变大写) NSString *upLetter = [string uppercaseString];
(全变小写) NSString *lowLetter = [string lowercaseString];
(首字母大写) NSString *firstUpLetter = [string capitalizedString];
是否以某个字符串开始 BOOL hasResult = [string hasPrefix:@"http"];
是否以某个字符串结束 BOOL hasResult = [string hasSuffix:@".com"];
再来总结两种字符串有区别的方法:
拼接字符串 不可变 NSString *string = [string stringByAppendingString:@"天才"];
可变 [string appendString:@"汗水"];
format: 万能公式 NSInteger number = 123;
[string appendFormat:@"%ld", number];
同上 [string appendFormat:@"1234"];
替换字符串
不可变
NSString *string = [string stringByReplacingCharactersInRange:NSMakeRange(3, 1) withString:@"他"];
可变
[string replaceCharactersInRange:[string rangeOfString:@"努力"] withString:@"汗水"];
NSMultableString(可变字符串)继承于NSString (不可变字符串),所以以上NSString的方法NSMultableString都可以使用.
接下来总结NSMultableString(可变字符串)特有的方法:
插入字符串 - [string insertString:@"当幸福来敲门" atIndex:6];
删除字符串 - [string deleteCharactersInRange:[string rangeOfString:@"的"]];
重置字符串 - [string setString:@"烟火里的尘埃"];
最后总结一下类型转换:
字符串转为其他类型:
NSString *string = [NSString stringWithFormat:@"123"];
NSInteger number = [string integerValue];
NSString *string = [NSString stringWithFormat:@"12.3"];
CGFloat floatNumber = [string floatValue];
基本数据类型转化为数值对象(NSNumber):
NSNumber *intNumber = [NSNumber numberWithInteger:5];
NSNumber *floatNumber = [NSNumber numberWithFloat:3.2];
NSNumber *charNumber = [NSNumber numberWithChar:'k'];
数值对象转化为基本数据类型:
NSInteger _intValue = [intNumber integerValue];
CGFloat _floatValue = [floatNUmber floatValue];
char _charValue = [charNumber charValue];
NSNumber类型的比较
NSNumber *num1 = [NSNumber numberWithInteger:12];
NSNumber *num2 = [NSNumber numberWithInteger:13];
NSInteger result = [num1 compare:num2];
结构体变量转化为NSValue(结构体对象类):
NSValue *point = [NSValue valueWithPoint:NSMakePoint(10, 20)];
NSValue *size = [NSValue valueWithSize:NSMakeSize(320, 480)];
NSValue *rect = [NSValue valueWithRect:NSMakeRect(0, 0, 375, 667)];
NSValue转化为结构体变量:
NSPoint p = [point pointValue];
NSSize s = [size sizeValue];
NSRect r = [rect rectValue];
万变不离其中,整理过后发现这样类比着记忆就清晰多了.