首页 > ios > ios01_字符串操作

ios01_字符串操作

一、字符串的操作
1.构建字符串
常用的字符串方法:stringWithFormat
字符串的附加(创建新的字符串):stringByAppendingString、stringByAppendingFormat
2.长度与索引字符
.length方法返回长度、characterAtIndex:(int)index返回索引字符
3.与C字符串相互转换
OC对象–>C:UTF8String、cStringUsingEncoding:NSUTF8StringEncoding
C–>OC对象:stringWithCString:(cstring) encoding:NSUTF8StringEncoding
4.将字符串写入文件和从文件读取字符串
NSString *path=[NSHomeDirectory() stringByAppendingPathComonent:”路径”]
myString writeToFile:path stomically:YES encoding:NSUTF8StringEncoding error:&error方法,成功YES,失败NO。

NSString *str=[NSString stringWithContentOfFile:path encoding:NSUTF8StringEncoding error:&error];

5.字符串分割成数组
componentsSeparatedByString:分隔符
6.提取字符串
NSString substringToIndex(<)/substringFromIndex(>=)
NSRange r;
r.location=4;
r.length=2;
用substringWithRange:r
7.搜索替换字符串
NSRange=rangeOfString:”搜索内容”
stringByReplacingCharactersInRange:(NSRange位置) withString:(NSString替换内容)
替换所有:stringByReplacingOccurrencesOfString:(NSString找到) withString:(NSString替换成)
8.改变大小写
uppercaseString//全部大写
lowercaseString//全部小写
capitalizedString//首字母大写
9.检查测试字符串
isEqualToString 相等?
hasPrefix 有前缀?
hasSuffix 有后缀?
10.从字符串中提取数字
intValue/boolValue/floatValue/doubleValue
11.可变字符串
11.1给字符串分配容量
NSMutableString *String = [NSMutableString stringWithCapacity:40];

11.2在已有字符串后面添加字符
NSMutableString *String1 = [[NSMutableString alloc] initWithString:@”This is a NSMutableString”];
[String1 appendFormat:[NSString stringWithFormat:@”, I will be adding some character”]];
NSLog(@”String1:%@”,String1);

11.3在已有字符串中按照所给出范围和长度删除字符
NSMutableString *String1 = [[NSMutableString alloc] initWithString:@”This is a NSMutableString”];
[String1 deleteCharactersInRange:NSMakeRange(0, 5)];
NSLog(@”String1:%@”,String1);
11.4在已有字符串后面在所指定的位置中插入给出的字符串
//insertString: atIndex:
NSMutableString *String1 = [[NSMutableString alloc] initWithString:@”This is a NSMutableString”];
[String1 insertString:@”Hi! ” atIndex:0];
NSLog(@”String1:%@”,String1);
11.5将已有的空符串换成其它的字符串
//setString:
NSMutableString *String1 = [[NSMutableString alloc] initWithString:@”This is a NSMutableString”];
[String1 setString:@”Hello Word!”];
NSLog(@”String1:%@”,String1);
11.6按照所给出的范围,和字符串替换的原有的字符
//-setString:
NSMutableString *String1 = [[NSMutableString alloc] initWithString:@”This is a NSMutableString”];
[String1 replaceCharactersInRange:NSMakeRange(0, 4) withString:@”That”];
NSLog(@”String1:%@”,String1);

  1. Criistian 9月 3rd, 2012 @ 02:22 | #1

    I hate my life but at least this makes it braaeble.

评论提交中, 请稍候...

留言


可以使用的标签: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>
Trackbacks & Pingbacks ( 0 )
  1. 还没有 trackbacks