NSString类详解

说到字符串NSString肯定每个开发IOS的都用过,它是Foundation框架下的一个核心处理字符串的类,掌握它非常有用。

1.属性:

最直接的属性有length,字符串长度

2.字符串的获取

//截取指定位置之后的字符串
- (NSString *)substringFromIndex:(NSUInteger)from;
//从0下标开始截取到指定位置的字符串
- (NSString *)substringToIndex:(NSUInteger)to;
//截取指定范围的字符串
- (NSString *)substringWithRange:(NSRange)range;
//截取字符串指定范围的字符
- (void)getCharacters:(unichar *)buffer range:(NSRange)range;

3.字符串的比较

最常用的比较相等,返回值为BOOL:

-(BOOL)isEqualToString:(NSString *)aString;
以NSComparisonResult作为比较返回结果的方法:

- (NSComparisonResult)compare:(NSString *)string;
- (NSComparisonResult)compare:(NSString *)string options:(NSStringCompareOptions)mask;
- (NSComparisonResult)compare:(NSString *)string options:(NSStringCompareOptions)mask range:(NSRange)rangeOfReceiverToCompare;
- (NSComparisonResult)compare:(NSString *)string options:(NSStringCompareOptions)mask range:(NSRange)rangeOfReceiverToCompare locale:(nullable id)locale; // locale arg used to be a dictionary pre-Leopard. We now accept NSLocale. Assumes the current locale if non-nil and non-NSLocale. nil continues to mean canonical compare, which doesn't depend on user's locale choice.
- (NSComparisonResult)caseInsensitiveCompare:(NSString *)string;
- (NSComparisonResult)localizedCompare:(NSString *)string;
- (NSComparisonResult)localizedCaseInsensitiveCompare:(NSString *)string;
- (NSComparisonResult)localizedStandardCompare:(NSString *)string NS_AVAILABLE(10_6, 4_0);

返回结果NScomparisonResult解释,

typedef NS_ENUM(NSInteger, NSComparisonResult) {
 NSOrderedAscending = -1L, //1 递增
 NSOrderedSame, //0  相等
 NSOrderedDescending//1 递减
 };
参数options:

NSStringCompareOptions 说明
NSCaseInsensitiveSearch 不区分大小写比较
NSLiteralSearch 区分大小写比较
NSBackwardsSearch 从字符串末尾开始搜索
NSAnchoredSearch 搜索限制范围的字符串
NSNumericSearch 按照字符串里的数字为依据,算出顺序
NSDiacriticInsensitiveSearch 忽略 "-" 符号的比较
NSWidthInsensitiveSearch 忽略字符串的长度,比较出结果
NSForcedOrderingSearch 忽略不区分大小写比较的选项
NSRegularExpressionSearch 只能应用于 rangeOfString:..., stringByReplacingOccurrencesOfString:...和 replaceOccurrencesOfString:...方法
比较原理,如果没有调用option的方法,比较是从两个字符串 的第一个字母开始一一对比,相同则比较下一个,不同则返回结果为升序或者降序,两个比较字符串建议长度一致,不一致也可以比较,比如:

@"agc" compare @" ab" //返回降序, 

@"abc" compare @"gd" //比较第一个字母之后就返回升序

参数range;

是决定前一个比较对象所需比较的范围。参考如下:

[@"AB" compare:@"ABC" options:0 range:NSMakeRange(0,1)] compares "A" to "ABC", not "A" to "A", and will return NSOrderedAscending


4.字符搜索

 //搜索基本//
//1.是否包含前缀(以str开头)
- (BOOL)hasPrefix:(NSString *)str;
//2.是否包含后缀(以str结尾)
- (BOOL)hasSuffix:(NSString *)str;
//3.获取公共前缀
- (NSString *)commonPrefixWithString:(NSString *)str options:(NSStringCompareOptions)mask;
//4.是否包含字符串
- (BOOL)containsString:(NSString *)str;
//5.本地化是否包含字符串(不区分大小写)
- (BOOL)localizedCaseInsensitiveContainsString:(NSString *)str;
//6.本地化是否包含字符串(标准)
- (BOOL)localizedStandardContainsString:(NSString *)str;
//7.本地化搜索字符串范围(标准)
- (NSRange)localizedStandardRangeOfString:(NSString *)str;

   //搜索字符串//
//8.搜索(指定字符串)
- (NSRange)rangeOfString:(NSString *)searchString;
//9.搜索(指定字符串,条件)
- (NSRange)rangeOfString:(NSString *)searchString options:(NSStringCompareOptions)mask;
//10.搜索(指定字符串,条件,范围)
- (NSRange)rangeOfString:(NSString *)searchString options:(NSStringCompareOptions)mask range:(NSRange)searchRange;
//11.搜索(指定字符串,条件,范围,本地化)
- (NSRange)rangeOfString:(NSString *)searchString options:(NSStringCompareOptions)mask range:(NSRange)searchRange locale:(nullable NSLocale *)locale;

   //搜索字符集合//
//12.搜索(指定字符集合)
- (NSRange)rangeOfCharacterFromSet:(NSCharacterSet *)searchSet;
//13.搜索(指定字符集合,条件)
- (NSRange)rangeOfCharacterFromSet:(NSCharacterSet *)searchSet options:(NSStringCompareOptions)mask;
//14.搜索(指定字符集合,条件,范围)
- (NSRange)rangeOfCharacterFromSet:(NSCharacterSet *)searchSet options:(NSStringCompareOptions)mask range:(NSRange)searchRange;

//15.用字符串的字符编码指定索引查找位置
- (NSRange)rangeOfComposedCharacterSequenceAtIndex:(NSUInteger)index;
//16.用字符串的字符编码指定区域段查找位置
- (NSRange)rangeOfComposedCharacterSequencesForRange:(NSRange)range;


字符串搜索主要是检测对象是否有前缀,后缀,子字符串等作用。

对于操作路径和扩展名有极大帮助【传送门

5.字符串拼接

- (NSString *)stringByAppendingString:(NSString *)aString;
- (NSString *)stringByAppendingFormat:(NSString *)format, ... NS_FORMAT_FUNCTION(1,2);
如果是添加路径的话可以使用:

- (NSString *)stringByAppendingPathComponent:(NSString *)str;

6.字符串转化为基本数据

@property (readonly) double doubleValue;
@property (readonly) float floatValue;
@property (readonly) int intValue;
@property (readonly) NSInteger integerValue NS_AVAILABLE(10_5, 2_0);
@property (readonly) long long longLongValue NS_AVAILABLE(10_5, 2_0);
@property (readonly) BOOL boolValue NS_AVAILABLE(10_5, 2_0); 
注意:这里需要提示一下,如果字符串内全是数字,则会全部转化(如果有小数点,转为float和double类型会全转,其他形式只取整数,),如果全是非数字,或者没有以数字开头,怎转化值为0,比如:@"dgtgwge566" //0   如果开头以数字开头,开始会提取到开头几个数字的,后面的提取不了,如:@"456dkhgeo90" //456

7.字符大小写转化

  //字符串大小写转换//
    NSString *string = @"string";

    NSLog(@"大写:         %@", string.uppercaseString);
    NSLog(@"小写:         %@", string.lowercaseString);
    NSLog(@"首字母大写:    %@", string.capitalizedString);
    //输出:   大写:         STRING
    //输出:   小写:         string
    //输出:   首字母大写:    String

//本地化(大写)
- (NSString *)uppercaseStringWithLocale:(nullable NSLocale *)locale; 
//本地化(小写)
- (NSString *)lowercaseStringWithLocale:(nullable NSLocale *)locale;
//本地化(首字母大写)
- (NSString *)capitalizedStringWithLocale:(nullable NSLocale *)locale;

8.字符串分行分段

   //分行//
//1.指定范围,分行取字符串
- (void)getLineStart:(nullable NSUInteger *)startPtr end:(nullable NSUInteger *)lineEndPtr contentsEnd:(nullable NSUInteger *)contentsEndPtr forRange:(NSRange)range;
//2.获取指定范围该行的范围
- (NSRange)lineRangeForRange:(NSRange)range;

   //分段//
//3.指定范围,分段取字符串
- (void)getParagraphStart:(nullable NSUInteger *)startPtr end:(nullable NSUInteger *)parEndPtr contentsEnd:(nullable NSUInteger *)contentsEndPtr forRange:(NSRange)range;
//4.获取指定范围该段落的范围
- (NSRange)paragraphRangeForRange:(NSRange)range;

  //字符串分行,分段//
    NSString *string = @"123 456\nABC,DEF\nabc.def";
    //获取该行的范围(指定范围)
    NSRange range1 = [string lineRangeForRange:NSMakeRange(0, 10)];
    NSLog(@"%ld 行长度:     %ld", range1.location, range1.length);
    //输出:       0 行长度:     16

    //获取该段落范围(指定范围)
    NSRange range2 = [string paragraphRangeForRange:NSMakeRange(0, 3)];
    NSLog(@"%ld 段落长度:   %ld", range2.location, range2.length);
    //输出:       0 段落长度:   8

9.字符串列举条件


NSStringEnumerationOptions 说明
NSStringEnumerationByLines 按行
NSStringEnumerationByParagraphs 按段落
NSStringEnumerationByComposedCharacterSequences 按字符顺序
NSStringEnumerationByWords 按单词,字
NSStringEnumerationBySentences 按句子
NSStringEnumerationReverse 反向遍历
NSStringEnumerationSubstringNotRequired 不需要子字符串
NSStringEnumerationLocalized 本地化
//字符串列举//    
   NSString *string = @"123456\nABCDEF\nabcdef
    //1.列举(按行)
   [string enumerateLinesUsingBlock:^(NSString * _Nonnull line, BOOL * _Nonnull stop) {
       NSLog(@"每行:   %@", line);
   }];
    //输出:    每行:   123456
    //输出:    每行:   ABCDEF
    //输出:    每行:   abcdef


    //2.列举(范围,条件)
    [string enumerateSubstringsInRange:NSMakeRange(5, 10) options:NSStringEnumerationByLines usingBlock:^(NSString * _Nullable substring, NSRange substringRange, NSRange enclosingRange, BOOL * _Nonnull stop) {

        NSLog(@"%@", substring);
        NSLog(@"%ld   %ld", substringRange.location, substringRange.length);
        NSLog(@"%ld   %ld", enclosingRange.location, enclosingRange.length);

    }];

10字符串编码与转换

//1.选择编码,是否允许有损编码【重要】
- (nullable NSData *)dataUsingEncoding:(NSStringEncoding)encoding allowLossyConversion:(BOOL)lossy;
//2.选择编码
- (nullable NSData *)dataUsingEncoding:(NSStringEncoding)encoding;
//3.判断是否可以无损编码
- (BOOL)canBeConvertedToEncoding:(NSStringEncoding)encoding;

//4.C字符编码转换
- (nullable __strong const char *)cStringUsingEncoding:(NSStringEncoding)encoding;
//5.判读C字符转化是否可以成功
- (BOOL)getCString:(char *)buffer maxLength:(NSUInteger)maxBufferCount encoding:(NSStringEncoding)encoding;
//6.指定缓存区转换
- (BOOL)getBytes:(nullable void *)buffer maxLength:(NSUInteger)maxBufferCount usedLength:(nullable NSUInteger *)usedBufferCount encoding:(NSStringEncoding)encoding options:(NSStringEncodingConversionOptions)options range:(NSRange)range remainingRange:(nullable NSRangePointer)leftover;

//7.对字符串进行编码时所需的最大字节数
- (NSUInteger)maximumLengthOfBytesUsingEncoding:(NSStringEncoding)enc;
//8.对字符串进行编码时所需的字节数
- (NSUInteger)lengthOfBytesUsingEncoding:(NSStringEncoding)enc;

//9.可用字符串编码
+ (const NSStringEncoding *)availableStringEncodings; 
//10.本地化编码名称
+ (NSString *)localizedNameOfStringEncoding:(NSStringEncoding)encoding;
//11.默认C字符串编码
+ (NSStringEncoding)defaultCStringEncoding;


11.字符串分割

NSCharacterSet集合

NSCharacterSet 说明
controlCharacterSet 控制符
whitespaceCharacterSet 空格符
whitespaceAndNewlineCharacterSet 空格换行符
decimalDigitCharacterSet 小数
letterCharacterSet 文字
lowercaseLetterCharacterSet 小写字母
uppercaseLetterCharacterSet 大写字母
nonBaseCharacterSet 非基础
alphanumericCharacterSet 数字字母
decomposableCharacterSet 可分解
illegalCharacterSet 非法
punctuationCharacterSet 标点
capitalizedLetterCharacterSet 大写
symbolCharacterSet 符号
newlineCharacterSet 换行符
 //字符串分割//
    NSString *string = @"A_B_c_D_E_F";

    //分割(指定字符串)
    NSArray *resultArr1 = [string componentsSeparatedByString:@"_"];
    NSLog(@"%@", resultArr1);
    //输出:   (A, B, c, D, E, F)

    //分割(指定字符集合)
    NSArray *resultArr2 = [string componentsSeparatedByCharactersInSet:[NSCharacterSet lowercaseLetterCharacterSet]];
    NSLog(@"%@", resultArr2);    
    //输出:   ("A_B_" , "_D_E_F")

12.字符串操作(修剪,替换,折叠,填充)


 NSString *string = @"3EWRs a;af";

    //修剪//
    NSString *result1 = [string stringByTrimmingCharactersInSet:[NSCharacterSet lowercaseLetterCharacterSet]];
    NSLog(@"%@", result1);
    //输出:   3EWRs a;


    //填充//
    NSString *result2 = [string stringByPaddingToLength:20 withString:@"填充" startingAtIndex:1];
    NSLog(@"%@", result2);
    //输出:   3EWRs a;af充填充填充填充填充填


    //折叠//
    NSString *result3 = [string stringByFoldingWithOptions:NSNumericSearch locale:[NSLocale systemLocale]];
    NSLog(@"%@", result3);
    //输出:   3EWRs a;af


    //替换//
    //替换(指定字符串)
    NSString *result4 = [string stringByReplacingOccurrencesOfString:@" " withString:@"替换"];
    NSLog(@"%@", result4);
    //输出:   3EWRs替换a;af


    //替换(指定字符串,条件,范围)
    NSString *result5 = [string stringByReplacingOccurrencesOfString:@"a" withString:@"替换" options:NSRegularExpressionSearch range:NSMakeRange(0, string.length - 2)];
    NSLog(@"%@", result5);
    //输出:   3EWRs 替换;af


    //替换(指定范围)
    NSString *result6 = [string stringByReplacingCharactersInRange:NSMakeRange(0, string.length) withString:@"替换"];
    NSLog(@"%@", result6);
    //输出:   替换

13.字符串写入

//字符串写入//
    //写入到指定路径,编码的文件中
    [string writeToFile:@"/Users/Desktop/LuisX.txt" atomically:YES encoding:NSUTF8StringEncoding error:nil];

    //写入到指定URL,编码的文件中
    [string writeToURL:[NSURL URLWithString:@"file://LuisX.text"] atomically:YES encoding:NSUTF8StringEncoding error:nil];


14NSMutableString的介绍

NSMutableString是NSString的字类,可以动态的扩展字符串。

初始化也可以分配容量

 //字符串分配容量//

   //1.初始化容量为Capacity大小的字符串  (需要手动释放内存)
   NSMutableString *mutableStr1 = [[NSMutableString alloc] initWithCapacity:20];

   //2.初始化容量为Capacity大小的字符串  (不需要手动释放内存)
   NSMutableString *mutableStr2 = [NSMutableString stringWithCapacity:20];

扩展方法

 NSMutableString *str = [NSMutableString stringWithString:@"string"];

    //插入//
    [str insertString:@"123" atIndex:2];
    NSLog(@"%@", str);
    //输出:   st123ring


    //删除//
    [str deleteCharactersInRange:NSMakeRange(2, 2)];
    NSLog(@"%@", str);
    //输出:   st3ring


    //拼接//
    [str appendString:@"456"];
    NSLog(@"%@", str);
    //输出:   st3ring456


    //格式化拼接//
    [str appendFormat:@"7 89"];
    NSLog(@"%@", str);
    //输出:   st3ring4567 89


    //设置新字符串//
    [str setString:@"string"];
    NSLog(@"%@", str);
    //输出:   string

    //字符串替换//
    //1.指定范围替换
    [str1 replaceCharactersInRange:NSMakeRange(2, 2) withString:@"123"];
    NSLog(@"%@", str1);
    //输出:   st123ng


    //2.指定字符串,条件,范围替换
    [str1 replaceOccurrencesOfString:@"123" withString:@"--" options:NSRegularExpressionSearch range:NSMakeRange(0, str1.length)];
    NSLog(@"%@", str1);
    //输出:   st--ng

本文转自: http://www.jianshu.com/p/d3f343b71cc2








评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值