NSString一些常用方法
从文件创建字符串 1 2 3 4 NSString *path = [[NSBundlemainBundle ] pathForResource:@"astring.text" ofType:nil ];NSString *astring = [[NSString alloc] initWithContentsOfFile:path];NSLog (@"astring:%@" ,astring);[astring release];
用字符串创建字符串,并写入到文件 [astring writeToFile: path atomically: YES];
isEqualToString方法 BOOL result = [astring01 isEqualToString:astring02];
compare方法(comparer返回的三种值) BOOL result = [astring01 compare:astring02] == NSOrderedSame 或者NSOrderedAscending 或者NSOrderedDescending
不考虑大小写比较字符串 1 2 3 BOOL result = [astring01 caseInsensitiveCompare:astring02] == NSOrderedSame ;BOOL result = [astring01 compare:astring02options:NSCaseInsensitiveSearch | NSNumericSearch ] == NSOrderedSame ; //NSCaseInsensitiveSearch :不区分大小写比较 NSLiteralSearch :进行完全比较,区分大小写 NSNumericSearch :比较字符串的字符个数,而不是字符值。
输出大写或者小写字符串 1 2 3 NSLog (@"string1:%@" ,[string1 uppercaseString ]); NSLog (@"string2:%@" ,[string2 lowercaseString ]); NSLog (@"string2:%@" ,[string2 capitalizedString ]);
查找字符串某处是否包含其它字符串 1 2 3 4 5 NSString *string1 = @"This is a string" ; NSString *string2 = @"string" ; NSRange range = [string1 rangeOfString:string2 ]; int location = range .location; int leight = range .length;
字符串截取
从字符串的开头一直截取到指定的位置,但不包括该位置的字符
NSString *string2 = [string1 substringToIndex:3];
以指定位置开始(包括指定位置的字符),并包括之后的全部字符
NSString *string2 = [string1 substringFromIndex:3];
按照所给出的位置,长度,任意地从字符串中截取子串
NSString *string2 = [string1 substringWithRange:NSMakeRange(0, 4)];
按照固定长度生成空字符串 NSMutableString *String = [NSMutableString stringWithCapacity:40 ];
把一个字符串接在另一个字符串的末尾 1 2 [String1 appendString: [String1 appendFormat:[NSString stringWithFormat:@", I will be adding some character"]];
在指定位置插入字符串 [String1 insertString: @"Hi! " atIndex: 0 ];
setString: NSMutableString *String1 = [[NSMutableString alloc ] initWithString :@"This is a NSMutableString" ];
[String1 setString :@"Hello Word!" ];
用指定字符串替换字符串中某指定位置、长度的字符串 1 2 NSMutableString *String1 = [[NSMutableString alloc] initWithString: @"This is a NSMutableString" ]; [String1 replaceCharactersInRange: NSMakeRange(0 , 4 ) withString: @"That" ];
检查字符串是否以另一个字符串开头 1 2 [String1 hasPrefix:@"NSString" ] = = 1 ? NSLog(@ "YES" ) : NSLog(@ "NO" ) [String1 hasSuffix:@".txt" ] = = 1 ? NSLog(@ "YES" ) : NSLog(@ "NO" )
扩展路径 NSString * Path =
NSString * absolutePath = [Path stringByExpandingTildeInPath];