NSMutableString的常见用法

1.给字符串分配容量

stringWithCapacity:

NSMutableString *String;

String = [NSMutableString stringWithCapacity:40];

2.在已有字符串后面添加字符

appendString: and appendFormat:

NSMutableString *String1 = [[NSMutableString alloc] initWithString:@"This is a NSMutableString"];

[String1 appendString:@", I will be adding some character"];

[String1 appendFormat:[NSString stringWithFormat:@", I will be adding some character"]];

NSLog(@"String1:%@",String1);

3.在已有字符串中按照所给出范围和长度删除字符

deleteCharactersInRange:

NSMutableString *String1 = [[NSMutableString alloc] initWithString:@"This is a NSMutableString"];

[String1 deleteCharactersInRange:NSMakeRange(0, 5)];

NSLog(@"String1:%@",String1);

4.在已有字符串后面在所指定的位置中插入给出的字符串

-insertString: atIndex:

NSMutableString *String1 = [[NSMutableString alloc] initWithString:@"This is a NSMutableString"];

[String1 insertString:@"Hi! " atIndex:0];

NSLog(@"String1:%@",String1);

5.将已有的空符串换成其它的字符串

-setString:

NSMutableString *String1 = [[NSMutableString alloc] initWithString:@"This is a NSMutableString"];

[String1 setString:@"Hello Word!"];

NSLog(@"String1:%@",String1);

6.按照所给出的范围,和字符串替换的原有的字符

-setString:

NSMutableString *String1 = [[NSMutableString alloc] initWithString:@"This is a NSMutableString"];

[String1 replaceCharactersInRange:NSMakeRange(0, 4) withString:@"That"];

NSLog(@"String1:%@",String1);

7.判断字符串内是否还包含别的字符串(前缀,后缀)

01:检查字符串是否以另一个字符串开头- (BOOL) hasPrefix: (NSString *) aString;

NSString *String1 = @"NSStringInformation.txt";

[String1 hasPrefix:@"NSString"] = = 1 ?  NSLog(@"YES") : NSLog(@"NO");

[String1 hasSuffix:@".txt"] = = 1 ?  NSLog(@"YES") : NSLog(@"NO");

你可能感兴趣的:(NSMutableString的常见用法)