[学习笔记]stringByReplacingOccurrencesOfString返回值的两种情况

来源:互联网 发布:mac屏幕红色 编辑:程序博客网 时间:2024/05/08 02:22

NSString 常用

Objective-c之NSString(NSMutableString)
2011-06-08 15:13
 

1、初始化字符串一 

 

[[NSString alloc] initWithFormat:@"%d",10]; 

 

 

2、初始化字符串二

 

[[NSString alloc] initWithCString:@"字符串内容"] 

 

 

3、字符串的替换

注:将字符串中的参数进行替换

参数1:目标替换值

参数2:替换成为的值

参数3:类型为默认:NSLiteralSearch

参数4:替换的范围

 

[str replaceOccurrencesOfString:@"1" withString:@"222" options:NSLiteralSearch range:NSMakeRange(0, [str length])]; 

 

 

4、给字符串分配容量

 

  NSMutableString *String;
  String = [NSMutableString stringWithCapacity:40]; 

 

 

5、追加字符串

 

 NSMutableString *String1 = [[NSMutableString alloc] initWithString:@"This is a NSMutableString"];
 [String1 appendFormat:[NSString stringWithFormat:@", I will be adding some character"]]; 

 

 

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

 

 NSMutableString *String1 = [[NSMutableString alloc] initWithString:@"This is a NSMutableString"];
 [String1 deleteCharactersInRange:NSMakeRange(0, 5)]; 

 

 

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

 

NSMutableString *String1 = [[NSMutableString alloc] initWithString:@"This is a NSMutableString"];
[String1 insertString:@"Hi! " atIndex:0]; 

 

 

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

 

 NSMutableString *String1 = [[NSMutableString alloc] initWithString:@"This is a NSMutableString"];
 [String1 replaceCharactersInRange:NSMakeRange(0, 4) withString:@"That"]; 

 

 

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

 

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

 

 

10、返回一个数组,包含已经由一个给定的分隔符分为接收器串。

- (NSArray*)componentsSeparatedByString:(NSString*)NString

参数
分离器
分隔符的字符串。

 

 

 

NSString *list = @"Norman, Stanley, Fletcher";
NSArray *listItems = [list componentsSeparatedByString:@", "];
listItems包含了:

{ @"Norman", @"Stanley", @"Fletcher" }.

 

 

 

 

11、是否包含该字符串

 

 

NSRange range = [@"字符串--A" rangeOfString:“是否包含--B”];


if (range.location == NSNotFound)

{//不包含

}

else

{//包含

}

分类: iOS Dev--http://www.cnblogs.com/kikee/archive/2011/11/02/2233257.html


第一种(有发生替换):
如:
NSString * s = @"sss";
NSString * x = [s stringByReplacingOccurrencesOfString:@"s" withString:@"x"];
返回一个新的指针,内容是@"xxx"。新指针的retainCount是1,不可以手动release,会autorelease。

第二种(没有发生替换):
如:
NSString * s = @"sss";
NSString * x = [s stringByReplacingOccurrencesOfString:@"y" withString:@"x"];
因为没有发生替换,所以返回值还是原来的指针,内容还是@"sss"。这时候s的retainCount会被加1。
相当于NSString * x = [[s retain] autorelease];

建议:
如果需要多次替换字符串中的字符,最好不要使用stringByReplacingOccurrencesOfString。应该使用NSMutableString的实例方法replaceOccurrencesOfString:withString:options:range:。

http://blog.sina.com.cn/s/blog_8764c3140100wxc3.html




0 0
原创粉丝点击