繼續NSString,由於用的多,所以應該重點掌握 1、求字符串長度 [cpp] NSString *myName = @"AOBAMA"; int length = (int)[myName length];//發現返回值類型是NSUInteger,不強轉有警告,自己也不知道強轉是不是常用的方法,望看到的網友能告知一下 NSLog(@"字符串的長度是:%d",length); if ([myName length] > 5) { NSLog(@"AAAAA");//打印AAAAA } 2、字符串的相關轉換 改變大小寫 [cpp] NSString *string = @"Where are You,Boy!"; //都大寫 NSLog(@"%@",[string uppercaseString]);//打印WHERE ARE YOU,BOY! //都小寫 NSLog(@"%@",[string lowercaseString]);//打印where are you,boy! //所有單詞首字母大寫,其它字母小寫 NSLog(@"%@",[string capitalizedString]);//打印Where Are You,Boy! 將字符串轉化成基本數據類型 [cpp] NSString *aboutFloat = @"3.14"; NSString *aboutBool = @"NO"; NSLog(@"%f",[aboutFloat floatValue]);//打印3.140000 NSLog(@"%d",[aboutBool boolValue]);//打印0 //把float型轉化為整型 NSLog(@"%d",[aboutFloat intValue]);//打印3 把兩個字符串合並成一個字符串 [cpp] //方法一 NSString *str1 = @"Hello"; NSString *str2 = @" World"; NSString *str3 = [[NSString alloc]initWithFormat:@"%@%@",str1,str2]; NSLog(@"str1與str2合並成str3的結果為:%@",str3);//打印結果:str1與str2合並成str3的結果為:Hello World //方法二 NSString *str4 = [str1 stringByAppendingString:str2]; NSLog(@"str1與str2合並成str4的結果為:%@",str4);//打印結果:str1與str2合並成str4的結果為:Hello World //連接多個字符串 NSString *str5 = [str1 stringByAppendingFormat:@"%@%@%@",str1,str2,str3]; NSLog(@"str5為:%@",str5);//打印結果:str5為:HelloHello WorldHello World 3、是否以一個字符串開頭hasPrefix:,是否以一個字符串結尾hasSuffix [cpp] NSString *str6 = @"who are you"; BOOL isStart1 = [str6 hasPrefix:@"wh"]; BOOL isStart2 = [str6 hasPrefix:@"h"]; BOOL isEnd1 = [str6 hasSuffix:@"u"]; BOOL isEnd2 = [str6 hasSuffix:@"o"]; NSLog(@"結果:%d,,,%d,,,%d,,,%d",isStart1,isStart2,isEnd1,isEnd2);//結果:1,,,0,,,1,,,0 4、將字符串按規則截取成數組 [cpp] NSString *str7 = @"you/have/a/baby"; NSArray *array = [str7 componentsSeparatedByString:@"/"]; NSLog(@"%@",array);//數組可以直接打印不用遍歷 /*打印結果 ( you, have, a, baby ) */ 5、字符串的截取 [cpp] NSString *str8 = [str7 substringFromIndex:2];//從第二個位置開始街區包括2,當然以0開頭 NSLog(@"%@",str8);// u/have/a/baby NSString *str9 = [str7 substringToIndex:5];//從開始到規定的位置,但不包括該位置 NSLog(@"%@",str9);// you/h //根據范圍截取 NSRange range = NSMakeRange(2, 3);//先定義范圍,也可以這樣定義NSRange range = {2,3}; NSLog(@"location..%ld length...%ld",range.location,range.length);// location..2 length...3 range.location = 3;//包括2 range.length =4;//從2開始長度為3的子字符串 NSLog(@"location..%ld length...%ld",range.location,range.length);// location..3 length...4 NSString *str10 = [str7 substringWithRange:range]; NSLog(@"%@",str10);// /hav 6、字符串查詢 [cpp] www.2cto.com NSRange range2 = [str7 rangeOfString:@"have"]; NSRange range3 = [str7 rangeOfString:@"aaa"]; NSLog(@"location1...%ld",range2.location); NSLog(@"location2...%ld",range3.location); 打印結果: location1...4 location2...9223372036854775807 我們可以根據要查詢的字符串在源字符串中的位置來判斷查找結果。 NSMutableString的相關用法