NSString
NSString对象是用来处理字符串的常用类,下面来看它的一些用法:
//创建
NSString *string1 = @"hello";
string1 = [[NSString alloc] initWithString:@"hello1"];
string1 = [[NSString alloc] initWithFormat:@"hello %@",string1]; //拼接
string1 = [NSString stringWithString:@"hello1"]; //类方法创建
//比较字符串的值是否相同(注意与isEqual:的区别)
BOOL isEquals = [string1 isEqualToString:string2];
//字符串比较
//逐个字符地进行比较ASCII值的大小,其结果为NSComparisonResult枚举,包括升序、相同、降序
NSComparisonResult result = [string1 compare:string2];
//忽略大小写比较
NSComparisonResult result = [string1 caseInsensitiveCompare: string2];
//获取字符串长度
NSInteger len = [string length];
//转化字符串的大小写
//转成大写
[string uppercaseString];
//转成小写
[string lowercaseString];
//首字符大写,其他的变成小写
[string capitalizedString];
//数值转化(int、float、double、integer、longlong)
float value = [string floatValue];
//字符串的截取
//从开始位置截取到下标为3的字串(不包括3)
NSString *stringnews = [string substringToIndex:3];
//从第3个字符开始截取到尾部(包括3)
stringnews = [string substringFromIndex:3];
//截取range部分的字串
NSRange range = {1,3};
stringnews = [string substringWithRange:range];
//字符串拼接
NSString *stringnew = [string stringByAppendingString:@"iOS"];
stringnew = [string stringByAppendingFormat:@"%@",@"iOS"];
//字符串查找
NSRange rang = [string rangeOfString:@"iOS"];
//是否以“iOS”开头
BOOL hasprefix = [@"" hasPrefix:@"iOS"];
//是否以“iOS”结尾
BOOL hassuffix = [@"" hasSuffix:@"iOS"];
//字符串替换
NSString *stringnew = [@"123456" stringByReplacingOccurrencesOfString:@"123" withString:@"321"]
//取出字符串中指定位置的char
unichar c = [string characterAtIndex:3];
//过滤头尾的指定字符串
NSString *stringnew = [@"***1234***56***" stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"*"]]
NSMutableString
NSMutableString是NSString的子类,提供了更多的对字符串的操作:
//插入字符串
[string1 insertString:@"可变" atIndex:0];
//删除指定范围的字串
NSMutableString *string = [NSMutableString stringWithString:@"hello"];
NSRange range = {1,3};
[string deleteCharactersInRange:range];
//替换字符串
NSMutableString *string = [NSMutableString stringWithString:@"hello"];
NSRange ranges = [string rangeOfString:@"ll"];//先查找出需要替换字符串的范围
[string replaceCharactersInRange:ranges withString:@"ee"];
网友评论