黑马程序员技术交流社区
标题:
OC字符串操作2
[打印本页]
作者:
豆豆是只喵
时间:
2015-10-11 18:14
标题:
OC字符串操作2
//--------操作动态字符串--NSMutableString----------------------------------------------------
NSMutableString *mstr = [[NSMutableString alloc] init];
NSString *str1 = @"This is a example.";
//创建可变字符串
mstr = [NSMutableString stringWithString:str1];
//插入字符
[mstr insertString:@"very easy " atIndex:10];
//删除一些字符
[mstr deleteCharactersInRange:NSMakeRange(10,5)];
//查找并删除
NSRange substr = [mstr rangeOfString:@"example"]; //字符串查找,可以判断字符串中是否有
if (substr.location != NSNotFound) {
[mstr deleteCharactersInRange:substr];
}
//重新设置字符串
[mstr setString:@"This is string AAA"];
//替换字符串
[mstr replaceCharactersInRange:NSMakeRange(15, 2) withString:@"BBB"]; //从第15个字符串处替换掉后2个字符串
//查找第一个并替换
NSString *search = @"This is";
NSString *replace = @"An example of";
substr = [mstr rangeOfString:search];
if (substr.location != NSNotFound) {
[mstr replaceCharactersInRange:substr withString:replace]; //把第1个遇到的substr替换为replace
NSLog(@"%@",mstr);
}
//查找全部匹配的,并替换
search = @"a";
replace = @"X";
substr = [mstr rangeOfString:search];
while (substr.location != NSNotFound) {
[mstr replaceCharactersInRange:substr withString:replace];
substr = [mstr rangeOfString:search];
}
NSLog(@"%@",mstr);
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2