ios开发之字符串操作(三)

本文详细介绍了iOS开发中字符串操作的基础与进阶,包括获取长度、截取、拼接、比较、搜索、替换、转换大小写以及前缀匹配等核心功能,帮助开发者深入掌握NSString的使用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

ios提供的字符串操作中有两个操作是最基本的。

获取字符串长度

@property (readonly) NSUInteger length;

获取下标对应的字符

- (unichar)characterAtIndex:(NSUInteger)index;
NSString *str=@"你好,世界!";

NSLog(@"length %lu",[str length]);

unichar ch=[str characterAtIndex:1];

NSLog(@"ch = %C",ch);

输出

2017-03-15 04:03:14.430 objc-base[2000:339489] length 6
2017-03-15 04:03:14.431 objc-base[2000:339489] ch = 好

其他许多字符串操作都是建立在以上两个操作之上的。

获取字符序列

获取字符串区间内的字符序列

- (void)getCharacters:(unichar *)buffer range:(NSRange)range;

获取字符串的字符序列

- (void)getCharacters:(unichar *)buffer;
NSString *str=@"你好,世界!";

unichar chs[6];

[str getCharacters:chs range:NSMakeRange(3, 2)];

NSLog(@"%C%C",chs[0],chs[1]);

[str getCharacters:chs];

NSLog(@"%C%C%C%C%C%C",chs[0],chs[1],chs[2],chs[3],chs[4],chs[5]);

输出

2017-03-15 04:15:28.138 objc-base[2046:347738] 世界
2017-03-15 04:15:28.138 objc-base[2046:347738] 你好,世界!

截取字符串

截取字符串区间内的字符串

- (NSString *)substringWithRange:(NSRange)range;

截取下标开始的字符串

- (NSString *)substringFromIndex:(NSUInteger)from;

截取下标结束的字符串(不包含下标)

- (NSString *)substringToIndex:(NSUInteger)to;
NSString *str=@"你好,世界!";

NSString *str1=[str substringWithRange:NSMakeRange(1, 3)];

NSLog(@"str1 = %@",str1);

NSString *str2=[str substringFromIndex:1];

NSLog(@"str2 = %@",str2);

NSString *str3=[str substringToIndex:3];

NSLog(@"str3 = %@",str3);

输出

2017-03-15 04:24:10.676 objc-base[2095:353965] str1 = 好,世
2017-03-15 04:24:10.678 objc-base[2095:353965] str2 = 好,世界!
2017-03-15 04:24:10.679 objc-base[2095:353965] str3 = 你好,

添加字符串

添加字符串

- (NSString *)stringByAppendingString:(NSString *)aString;

添加格式化字符串

- (NSString *)stringByAppendingFormat:(NSString *)format, ...
NSString *str=@"你好,世界!";

NSString *str1=[str stringByAppendingString:@"hello,world!"];

NSString *str2=[str stringByAppendingFormat:@"%@",@"hello,world!"];

NSLog(@"str1 = %@ str2 = %@",str1,str2);

输出

2017-03-15 04:32:31.090 objc-base[2120:359387] str1 = 你好,世界!hello,world! str2 = 你好,世界!hello,world!

字符串是否相等

比较字符串是否相等

- (BOOL)isEqualToString:(NSString *)aString;

是否以字符串开头

- (BOOL)hasPrefix:(NSString *)str;

是否以字符串结尾

- (BOOL)hasSuffix:(NSString *)str;
NSString *str=@"你好,世界!";

NSString *str1=@"你好,世界!";

NSLog(@"%d",[str isEqualToString:str1]);

NSString *str2=@"你好";

NSLog(@"%d",[str hasPrefix:str2]);

NSString *str3=@"世界!";

NSLog(@"%d",[str hasSuffix:str3]);

输出

2017-03-15 04:47:08.746 objc-base[2154:368999] 1
2017-03-15 04:47:08.747 objc-base[2154:368999] 1
2017-03-15 04:47:08.748 objc-base[2154:368999] 1

比较字符串

- (NSComparisonResult)compare:(NSString *)string options:(NSStringCompareOptions)mask 
range:(NSRange)rangeOfReceiverToCompare locale:(nullable id)locale; 

比较两个字符串的大小。返回类型为NSComparisonResult

typedef NS_ENUM(NSInteger, NSComparisonResult) 
{NSOrderedAscending = -1L, NSOrderedSame, NSOrderedDescending};

若前一个字符串小于后一个字符串则返回-1(NSOrderedAscending ),若相等则返回0(NSOrderedSame),若大于则返回1(NSOrderedDescending)。

参数string指定比较的字符串。参数rangeOfReceiverToCompare 指定比较的区间。参数mask 指定比较的方式,其类型为NSStringCompareOptions.

typedef NS_OPTIONS(NSUInteger, NSStringCompareOptions) {
    NSCaseInsensitiveSearch = 1,
    NSLiteralSearch = 2,        
    NSBackwardsSearch = 4,      
    NSAnchoredSearch = 8,   
    NSNumericSearch = 64,   
    NSDiacriticInsensitiveSearch NS_ENUM_AVAILABLE(10_5, 2_0) = 128,
    NSWidthInsensitiveSearch NS_ENUM_AVAILABLE(10_5, 2_0) = 256, 
    NSForcedOrderingSearch NS_ENUM_AVAILABLE(10_5, 2_0) = 512, 
    NSRegularExpressionSearch NS_ENUM_AVAILABLE(10_7, 3_2) = 1024
};

compare方法用到了以下项

NSCaseInsensitiveSearch
//不区分大小写比较 
NSLiteralSearch
//进行完全比较,区分大小写
NSNumericSearch
//按照字符串里的数字为依据,算出顺序。例如 Foo2.txt < Foo7.txt < Foo25.txt
NSDiacriticInsensitiveSearch
//忽略 "-" 符号的比较
NSWidthInsensitiveSearch
//忽略字符串的长度,比较出结果
NSForcedOrderingSearch
//忽略不区分大小写比较的选项,并强制返回 NSOrderedAscending 或者 NSOrderedDescending

它们都可以用逻辑“或”运算符组合在一起。

参数locale用于本地化。

其他比较方法

- (NSComparisonResult)compare:(NSString *)string options:(NSStringCompareOptions)mask 
range:(NSRange)rangeOfReceiverToCompare;
- (NSComparisonResult)compare:(NSString *)string options:(NSStringCompareOptions)mask;
- (NSComparisonResult)compare:(NSString *)string;
NSString *str1=@"hello,world!";

NSString *str2=@"HELLO,WORLD!";

NSLog(@"ret = %lu",[str1 compare:str2]);

NSLog(@"ret = %lu",[str1 compare:str2 options:NSCaseInsensitiveSearch]);

输出

2017-03-18 03:36:09.550 objc-base[2546:409402] ret = 1
2017-03-18 03:36:09.551 objc-base[2546:409402] ret = 0

不区分大小写比较字符串

- (NSComparisonResult)caseInsensitiveCompare:(NSString *)string;

本地化比较字符串

- (NSComparisonResult)localizedCompare:(NSString *)string;

本地化+不区分大小写比较字符串

- (NSComparisonResult)localizedCaseInsensitiveCompare:(NSString *)string;

本地化+标准比较字符串

- (NSComparisonResult)localizedStandardCompare:(NSString *)string

是否包含字符串

判断是否包含字符串

- (BOOL)containsString:(NSString *)str

判断是否包含本地化+不区分大小的字符串

- (BOOL)localizedCaseInsensitiveContainsString:(NSString *)str

判断是否包含本地化的字符串

- (BOOL)localizedStandardContainsString:(NSString *)str
NSString *str1=@"hello,world!";

NSString *str2=@"HELLO,WORLD!";

NSLog(@"ret = %d",[str1 containsString:str2]);

NSLog(@"ret = %d",[str1 localizedCaseInsensitiveContainsString:str2]);

输出

2017-03-18 03:48:52.647 objc-base[2591:417644] ret = 0
2017-03-18 03:48:52.648 objc-base[2591:417644] ret = 1

搜索字符串

搜索字符集中的字符

- (NSRange)rangeOfCharacterFromSet:(NSCharacterSet *)searchSet 
options:(NSStringCompareOptions)mask range:(NSRange)rangeOfReceiverToSearch;

参数searchSet指定字符集,参数rangeOfReceiverToSearch指定搜索的区间。参数mask指定搜索的方式
可能用到以下选项

 NSBackwardsSearch  由后向前搜索

其他搜索字符集方法

- (NSRange)rangeOfCharacterFromSet:(NSCharacterSet *)searchSet 
options:(NSStringCompareOptions)mask;
- (NSRange)rangeOfCharacterFromSet:(NSCharacterSet *)searchSet;

搜索字符串

- (NSRange)rangeOfString:(NSString *)searchString 
options:(NSStringCompareOptions)mask range:(NSRange)rangeOfReceiverToSearch 
locale:(nullable NSLocale *)locale

参数searchString是搜索的字符串,参数rangeOfReceiverToSearch是搜索的区间,参数locale用于本地化,参数mask是搜索的方式。其类型是NSStringCompareOptions,其可能值为

NSCaseInsensitiveSearch
//不区分大小写比较 
NSLiteralSearch
//进行完全比较,区分大小写
NSBackwardsSearch
//从后向前搜索
NSAnchoredSearch
//只考虑搜索的起始点(单独使用)或终止点(当与 NSBackwardsSearch  结合使用时)。
//这个方法可以用来检查前缀或者后缀,以及大小写不敏感(case-insensitive)
//或者音调不敏感(diacritic-insensitive)的比较。
NSRegularExpressionSearch
//使用正则表达式搜索

其他搜索方法

- (NSRange)rangeOfString:(NSString *)searchString 
options:(NSStringCompareOptions)mask 
range:(NSRange)rangeOfReceiverToSearch;
- (NSRange)rangeOfString:(NSString *)searchString 
options:(NSStringCompareOptions)mask;
- (NSRange)rangeOfString:(NSString *)searchString;

本地化+标准搜索字符串

- (NSRange)localizedStandardRangeOfString:(NSString *)str

拆分字符串

根据字符集字符拆分字符串

- (NSArray<NSString *> *)componentsSeparatedByCharactersInSet:(NSCharacterSet *)separator

根据字符串查分字符串

- (NSArray<NSString *> *)componentsSeparatedByString:(NSString *)separator;
NSString *str=@";hello;world";

NSArray *arr=[str componentsSeparatedByString:@";"];

NSLog(@"%@",arr);

NSArray *arr2=[str componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"o"]];

NSLog(@"%@",arr2);

输出

2017-03-19 01:02:36.327 objc-base[2888:476301] (
    "",
    hello,
    world
)
2017-03-19 01:02:36.329 objc-base[2888:476301] (
    ";hell",
    ";w",
    rld
)

替换字符串

- (NSString *)stringByReplacingOccurrencesOfString:(NSString *)target 
withString:(NSString *)replacement options:(NSStringCompareOptions)options 
range:(NSRange)searchRange

替换所有字符串。
参数target是要替换的字符串,参数replacement是替换的字符串,searchRange是搜索的区间。options指定搜索字符串的方式。其可能选项为

NSCaseInsensitiveSearch
//不区分大小写比较 
NSLiteralSearch
//进行完全比较,区分大小写
NSAnchoredSearch
//只考虑搜索的起始点(单独使用)或终止点(当与 NSBackwardsSearch  结合使用时)。
//这个方法可以用来检查前缀或者后缀,以及大小写不敏感(case-insensitive)
//或者音调不敏感(diacritic-insensitive)的比较。
NSRegularExpressionSearch
//使用正则表达式搜索

其他替换方法

- (NSString *)stringByReplacingOccurrencesOfString:(NSString *)target 
withString:(NSString *)replacement

替换区间内的字符串

- (NSString *)stringByReplacingCharactersInRange:(NSRange)range 
withString:(NSString *)replacement

参数range 为替换的区间。参数replacement为替换的字符串。

去除两端字符

- (NSString *)stringByTrimmingCharactersInSet:(NSCharacterSet *)set;

参数set指定字符集。

NSCharacterSet *set=[NSCharacterSet characterSetWithCharactersInString:@"{}|"];

NSString *str=@"{hello}|,|{world}";

NSString *str2=[str stringByTrimmingCharactersInSet:set];

NSLog(@"str = %@",str2);

输出

2017-03-23 04:01:27.351 objc-base[3862:678550] str = hello}|,|{world

填充字符串

- (NSString *)stringByPaddingToLength:(NSUInteger)newLength 
withString:(NSString *)padString startingAtIndex:(NSUInteger)padIndex;

参数newLength为填充后的字符串长度。参数padString为填充的字符串。参数padIndex为填充字符串开始的位置,第一次填充时使用。

NSString *str=@"hello,";

NSString *str1=[str stringByPaddingToLength:30 withString:@"world" startingAtIndex:2];

NSLog(@"str = %@",str1);

输出

2017-03-23 04:58:57.463 objc-base[3930:712084] str = hello,rldworldworldworldworldw

转为大写字符串

@property (readonly, copy) NSString *uppercaseString;

转为本地化大写字符串

@property (readonly, copy) NSString *localizedUppercaseString

转为地区化大写字符串

- (NSString *)uppercaseStringWithLocale:(nullable NSLocale *)locale
NSString *str=@"hello WORLD";

NSLog(@"str = %@",[str uppercaseString]);

NSLog(@"str = %@",[str localizedUppercaseString]);

NSLog(@"str = %@",[str uppercaseStringWithLocale:[NSLocale currentLocale]]);

输出

2017-03-19 01:36:15.529 objc-base[2939:496252] str = HELLO WORLD
2017-03-19 01:36:15.531 objc-base[2939:496252] str = HELLO WORLD
2017-03-19 01:36:15.532 objc-base[2939:496252] str = HELLO WORLD

转为小写字符串

@property (readonly, copy) NSString *lowercaseString;

转为本地化小写字符串

@property (readonly, copy) NSString *localizedLowercaseString

转为地区化小写字符串

- (NSString *)lowercaseStringWithLocale:(nullable NSLocale *)locale
NSString *str=@"hello WORLD";

NSLog(@"str = %@",[str lowercaseString]);

NSLog(@"str = %@",[str localizedLowercaseString]);

NSLog(@"str = %@",[str lowercaseStringWithLocale:[NSLocale currentLocale]]);

输出

2017-03-19 01:37:47.769 objc-base[2957:497549] str = hello world
2017-03-19 01:37:47.771 objc-base[2957:497549] str = hello world
2017-03-19 01:37:47.772 objc-base[2957:497549] str = hello world

转为首字母大写字符串

@property (readonly, copy) NSString *capitalizedString;

转为本地化首字母大写字符串

@property (readonly, copy) NSString *localizedCapitalizedString

转为地区化首字母大写字符串

- (NSString *)capitalizedStringWithLocale:(nullable NSLocale *)locale
NSString *str=@"hello WORLD";

NSLog(@"str = %@",[str capitalizedString]);

NSLog(@"str = %@",[str localizedCapitalizedString]);

NSLog(@"str = %@",[str capitalizedStringWithLocale:[NSLocale currentLocale]]);

输出

2017-03-19 01:39:16.674 objc-base[2978:498870] str = Hello World
2017-03-19 01:39:16.676 objc-base[2978:498870] str = Hello World
2017-03-19 01:39:16.677 objc-base[2978:498870] str = Hello World

返回相同的前缀

- (NSString *)commonPrefixWithString:(NSString *)str 
options:(NSStringCompareOptions)mask;

参数str是操作的字符串,参数mask是比较字符串的方式,其可能选项有

NSCaseInsensitiveSearch
//不区分大小写比较 
NSLiteralSearch
//进行完全比较,区分大小写
NSString *str1=@"hello,world!";
NSString *str2=@"hello,WORLD!";

NSLog(@"%@",[str1 commonPrefixWithString:str2 options:0]);

NSLog(@"%@",[str1 commonPrefixWithString:str2 options:NSCaseInsensitiveSearch]);

输出

2017-03-20 05:17:55.227 objc-base[3295:572367] hello,
2017-03-20 05:17:55.230 objc-base[3295:572367] hello,world!

返回数值

@property (readonly) double doubleValue;
@property (readonly) float floatValue;
@property (readonly) int intValue;
@property (readonly) NSInteger integerValue;
@property (readonly) long long longLongValue;
@property (readonly) BOOL boolValue; 

写入文件/url

- (BOOL)writeToFile:(NSString *)path atomically:(BOOL)useAuxiliaryFile 
encoding:(NSStringEncoding)enc error:(NSError **)error;
- (BOOL)writeToURL:(NSURL *)url atomically:(BOOL)useAuxiliaryFile 
encoding:(NSStringEncoding)enc error:(NSError **)error;
- (BOOL)writeToFile:(NSString *)path atomically:(BOOL)useAuxiliaryFile
- (BOOL)writeToURL:(NSURL *)url atomically:(BOOL)atomically

参数path指定文件/url路径,参数useAuxiliaryFile表示是否是原子操作—–原子操作使用辅助文件完成。参数enc指定编码方式,参数error在出错时获取出错信息。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值