标签:
NSMutableString 类 继承NSString类,那么NSString ??供的方法在NSMutableString中基本都可以使用,NSMutableString好比一个字符串链表,它可以任意的动态在字符串中添加字符 串 删除字符串 指定位置插入字符串,使用它来操作字符串会更加灵活。
NSMutableString和NSString的区别
// 改变了指针的指向, 并没有修改字符串
NSString *str = @"lnj";
str = @"lmj";
// 生成了一个新的字符串, 并没有修改字符串
NSString *newStr = [str substringFromIndex:1];
NSLog(@"str = %@", str);
NSLog(@"newStr = %@", newStr);
NSMutableString *strM = [NSMutableString string];
NSLog(@"strM = %@", strM);
// 修改原有字符串, 没有生成新的字符串
[strM appendString:@"lnj"];
NSLog(@"strM = %@", strM);
[strM appendString:@" v587"];
NSLog(@"strM = %@", strM);
NSMutableString *strM = [NSMutableString string];
NSLog(@"strM = %@", strM);
[strM appendString:@"lnj"];
NSLog(@"strM = %@", strM);
NSMutableString *strM = [NSMutableString string];
[strM appendFormat:@"/age is %i", 10];
NSMutableString *strM = [NSMutableString stringWithString:@"http://www.520it.com"];
// 一般情况下利用rangeOfString和deleteCharactersInRange配合删除指定内容
NSRange range = [strM rangeOfString:@"http://"];
[strM deleteCharactersInRange:range];
NSLog(@"strM = %@", strM);
NSMutableString *strM = [NSMutableString stringWithString:@"www.520it.com"];
[strM insertString:@"http://" atIndex:0];
NSLog(@"strM = %@", strM);
NSMutableString *strM = [NSMutableString stringWithString:@"http://www.520it.com/lnj.png"];
NSRange range = [strM rangeOfString:@"lnj"];
[strM replaceOccurrencesOfString:@"lnj" withString:@"jjj" options:0 range:range];
NSLog(@"strM = %@", strM);
NSMutalbeString *s1 = @”lnj”;
// 会报错
[strM insertString:@"my name is " atIndex:0];
从要求讲3个520it拼接在一起
会生成很多新的字符串
NSString *res = @"";
NSString *subStr = @"520";
// 1.拼接字符串
// res = [res stringByAppendingString:subStr];
// res = [res stringByAppendingString:@" "];
//
// res = [res stringByAppendingString:subStr];
// res = [res stringByAppendingString:@" "];
//
// res = [res stringByAppendingString:subStr];
// res = [res stringByAppendingString:@" "];
for (int i = 0; i < 3; ++i) {
res = [res stringByAppendingString:subStr];
res = [res stringByAppendingString:@" "];
}
// 2.删除末尾的空格
// res = [res stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
res = [res substringToIndex:res.length - 1];
NSLog(@"res = |%@|", res);
NSString *subStr = @"520it";
NSMutableString *res = [NSMutableString string];
// 1.拼接字符串
for (int i = 0; i < 3; ++i) {
[res appendString:subStr];
[res appendString:@" "];
}
// 2.删除空格
// [res replaceCharactersInRange:NSMakeRange(res.length - 1, 1) withString:@""];
[res deleteCharactersInRange:NSMakeRange(res.length - 1, 1)];
NSLog(@"res = |%@|", res);
标签:
原文地址:http://www.cnblogs.com/zhoudaquan/p/5017656.html