标签:
可变字符串(NSMutableString)
不可变字符串(NSString)创建之后就不能增删改
1、创建字符串
//1.静态 alloc new copy mutablecopy
NSString *str = @"hello world";
//2.alloc 空字符串对象
NSString *str2 = [[[NSString alloc] init] autorelease];
//3.alloc 有初始值
NSString *str3 = [[[NSString alloc] initWithString:str] autorelease];
//不要自己控制内存 工厂方法 便利器方法
NSString *str31 = [NSString stringWithString:str];
NSLog(@"%@", str31);
//4.字符串按照一定的格式拼接 age = 20 height = 170
NSString *str4 = [[[NSString alloc] initWithFormat:@"age=%d height=%d", age, height] autorelease];
NSString *str4 = [NSString stringWithFormat:@"age=%d height=%d", age, height];
NSLog(@"%@", str4);
2、length获取长度
NSUlnteger length = str.length;
3、获取子字符串
a. substringFromIndex:
b. substringToIndex:
c. substringWithRange:
typedef struct _NSRange {
NSUInteger location;
NSUInteger length;
} NSRange;
NSRange range = NSMakeRange(4, 8);
NSString *rangeStr = [str substringWithRange:range];
4、字符串的比较
a. isEqualToString:
b. compare:
typedef enum {
NSOrderedAscending = -1,//a<b
NSOrderedSame,//a=b
NSOrderedDescending//a>b
}NSComparisonResult;
5、字符串的查找
a.hasPrefix:
[url hasPrefix:@"http"]//url是以http开头
b.hasSuffix://是以什么结尾
c.rangeOfString://得到子字符串的起点和长度
6、字符串转化为相应的数据类型
a. intValue
b. boolValue
c. floatValue
d. doubleValue
NSString *priceStr = @"33.5";
float price = [priceStr floatValue];
7、数字转化为字符串 使用stringWithFormat:
int temp = 20;
NSString *tempStr = [NSString stringWithFormat:@"this costs $%d", temp];
可变字符串(NSMutableString)
@interface NSMutableString :NSString{
}//是继承与NSString的
1、创建可变字符串
NSMutableString *mstr2 = [NSMutableString stringWithCapacity:0];
NSMutableString *mStr = [[NSMutableString alloc] initWithCapacity:0];
2、追加可变字符串
[mStr appendString:@"四大名著"];
[mStr appendFormat:@"%d 大名著", num];
3、在某个位置插入一个字符串
[mStr insertString:@"《" atIndex:0];
[mStr insertString:@"》" atIndex:mStr.length];
4、字符串的替换
NSRange rge = [mStr rangeOfString:@"四大名著"];
[mStr replaceCharactersInRange:rge withString:@"三国压抑"];
5、删除一个字符串
NSRange yge = [mStr rangeOfString:@"压抑"];
[mStr deleteCharactersInRange:yge];
6、重新设置字符串的内容
[mStr setString:@"西游记"];
标签:
原文地址:http://www.cnblogs.com/zhaopengs/p/5070096.html