字符串NSString与NSMutableString常用方法

NSString

1、初始化

NSString *str1 = @"a OC Program";

2、初始化

NSString *str2 = [[NSString alloc] initWithFormat:@"字符串2:%d", 100];

3、初始化

NSString *str3 = [NSString stringWithFormat:@"%@ %d", @"类方法", 99];

4、初始化

char *c_string = "C语言常量字符串";
NSString *str4 = [[NSString alloc] initWithUTF8String:c_string];

5、提取特定索引的字符。在OC中,字符串中每一个组成字符都是一个UniChar类型

UniChar unch = [@"your name" characterAtIndex:0];

6、根据索引提取从索引(含)到最后的所有元素

NSString *str6 = [@"your name" substringFromIndex:2];

7、根据索引提取从最初位置到索引(不含索引位置)

NSString *str7 = [@"your name" substringToIndex:2];

8、根据范围提取字串(往后数)

NSRange range = {2, 3};
NSString *str8 = [@"your name" substringWithRange:range];

9、compare:通过unicode编码表比较

// 得到-1或0或1。下面result为-1
NSComparisonResult result = [@"a" compare:@"b"];

10、isEqualToString:判断两个字符串是否相等

BOOL result = [@"a" isEqualToString:@"b"];

11、hasPrefix:判断是否存在某前缀

BOOL result = [@"abc" hasPrefix:@"b"];

12、hasSuffix:判断是否存在某后缀

BOOL result = [@"abc" hasSuffix:@"b"];

13、containsString:判断是否包含某字符串

BOOL result = [@"abc" containsString:@"b"];

14、stringByAppendingString:拼接字符串,拼接结果以新字符串的形式返回

NSString *str14 = [@"abc" stringByAppendingString:@"efg"];

15、intValue,将数字字符串转换成整型数据

NSString *str15 = @"999";
int value = [str15 intValue];

16、字符串转数组。根据分隔符,分割字符串,以数组元素的形式返回

NSString *strArray = [@"guo" componentsSeparatedByString:@"guo"];
// 运行后strArray.count == 2

17、把字符串中的所有小写字母转换成大写字母

NSString *str = [@"aBcDef" uppercaseString];

18、把字符串中的所有大写字母转换成小写字母

NSString *str = [@"aBcDef" lowercaseString];

19、rangeOfString:(此方法只能检测到第一个出现的字串)

NSString *str1 = @"when i was young, i love a girl in neighbor class";
NSString *str2 =@"young";
NSRange rang = [str1 rangeOfString:str2];
NSLog(@"%d~%d", rang.location, rang.length);

NSMutableString

NSString是NSMutableString的父类,所有上面介绍的NSString的方法,NSMutableString都能够使用。

1、初始化

NSMutableString *mString = [[NSMutableString alloc] initWithString:@"123"];

2、初始化(给出预估空间大小)

NSMutableString *mString = [[NSMutableString alloc] initWithCapacity:10];

3、根据位置替换(有删除并插入的意思)成目标串

NSMutableString *mString = [[NSMutableString alloc] initWithString:@"123"];
NSRange range = {2, 3};
[mString replaceCharactersInRange:range withString:@"c"];

4、根据索引的位置插入一个目标串

NSMutableString *mString = [[NSMutableString alloc] initWithString:@"123"];
[mString insertString:@"abc" atIndex:2];
// 运行后mString == @"12abc3";

5、根据range删除子串

NSMutableString *mString = [[NSMutableString alloc] initWithString:@"123"];
NSRange range = {2, 1};
[mString deleteCharactersInRange:range];

5、拼接字符串

NSMutableString *mString = [[NSMutableString alloc] initWithString:@"123"];
[mString appendFormat:@"!"];
[mString appendString:@"456"];

 

posted @ 2018-04-21 01:02  码出境界  阅读(1246)  评论(0编辑  收藏  举报