我们在开发中很多时候都会遇到字符串截图,比如文本显示长度限制、自定义协议解析都会截取一部分字符串进行操作。
但是我们直接用系统方法substringToIndex
、substringFromIndex
、substringWithRange
截取字符串就能保证万无一失吗?一般情况下我的回答是的,但是...
NSString *str = @"🎊asdsd🎊asd🎊";
我们看下这段代码,如果打印str
的length
会是11吗?
[图片上传失败...(image-56fa49-1657456976062)]
现实总是啪啪打脸,为什么长度是14不是11呢?因为🎊
表情长度是2不是1,用转码工具进行Unicode
编码,得到的结果是\ud83c\udf8a
,这也解释了为什么这个表情长度是2的原因。
[图片上传失败...(image-b757a5-1657456976062)]
我们根据长度截取下字符串:
[图片上传失败...(image-dc648a-1657456976062)]
截取后表情编码变成了一半,我们在转码试试发现转出来的是乱码。
[图片上传失败...(image-c04a59-1657456976062)]
当时我们没注意这个问题,直接把截取字符串存到coreData
中,直接导致所有coreData
崩溃,所以我们在截取字符串的时候就要注意了。
问题找到了,原因也晓得了,现在就是如何处理。
rangeOfComposedCharacterSequenceAtIndex
这个函数可以获取当前位置所在字符的完整range,用这个我们就可以进行判断处理。
[图片上传失败...(image-cc4401-1657456976062)]
如果用substringToIndex:
截取字符串,判断to
前一位的字符长度是否大于1,如果大于1,用这个字符串的location
作为新的to
的值。
如果用substringFromIndex:
截取字符串,判断from
字符起始位置和from
是否相等,不等的话把字符location
+length
作为新的from
的值。
话不多说,直接上代码:
- (NSString *)sj_substringToIndex:(NSUInteger)to
{
if (to <= 0) {
return @"";
}
NSRange lastRange = [self rangeOfComposedCharacterSequenceAtIndex:to - 1];
if (lastRange.length > 1) {
return [self sj_substringToIndex:lastRange.location];
} else {
return [self sj_substringToIndex:to];
}
}
- (NSString *)sj_substringFromIndex:(NSUInteger)from
{
if (from < 0) {
return @"";
}
NSRange firstRange = [self rangeOfComposedCharacterSequenceAtIndex:from];
if (firstRange.location != from) {
return [self sj_substringFromIndex:(firstRange.location + firstRange.length)];
} else {
return [self sj_substringFromIndex:from];
}
}
- (NSString *)sj_substringWithRange:(NSRange)range
{
if (range.length == 0 || range.location + range.length > self.length) {
return @"";
}
NSInteger loc = range.location;
NSInteger len = range.length;
NSRange firstRange = [self rangeOfComposedCharacterSequenceAtIndex:loc];
NSRange lastRange = [self rangeOfComposedCharacterSequenceAtIndex:loc + len - 1];
if (firstRange.location != loc) {
len -= (firstRange.location + firstRange.length - loc);
loc = firstRange.location + firstRange.length;
}
if (lastRange.length > 1 && (lastRange.location + lastRange.length) > loc + len) {
len = lastRange.location - loc;
}
if (len <= 0) {
return @"";
} else {
return [self sj_substringWithRange:NSMakeRange(loc, len)];
}
}
直接添加个NSString
分类,用方法交换一下系统方法,这样整个工程就全部改了。
+ (void)load
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
Method oldMethod1 = class_getInstanceMethod([self class], @selector(substringToIndex:));
Method newMethod1 = class_getInstanceMethod([self class], @selector(sj_substringToIndex:));
method_exchangeImplementations(oldMethod1, newMethod1);
Method oldMethod2 = class_getInstanceMethod([self class], @selector(substringFromIndex:));
Method newMethod2 = class_getInstanceMethod([self class], @selector(sj_substringFromIndex:));
method_exchangeImplementations(oldMethod2, newMethod2);
Method oldMethod3 = class_getInstanceMethod([self class], @selector(substringWithRange:));
Method newMethod3 = class_getInstanceMethod([self class], @selector(sj_substringWithRange:));
method_exchangeImplementations(oldMethod3, newMethod3);
});
}
以为大功告成了吗?NO!NO!NO!!!
NSString *str = @"2022-07-10";
NSDateFormatter *f = [[NSDateFormatter alloc] init];
f.dateFormat = @"yyyy-MM-dd";
NSDate *date = [f dateFromString:str];
NSLog(@"date : %@", date);
测试一下上面代码,发现运行起来直接崩溃了。
[图片上传失败...(image-b8b7b1-1657456976062)]
[图片上传失败...(image-644aa8-1657456976062)]
定位下崩溃原因,发现dateFromString:
会执行到substringFromIndex
,并且str
长度是10,from
也是10,肯定会崩溃啊,为什么系统调用就不会?系统调用应该会有特殊处理,所以我们优化下我们的方法:
- (NSString *)sj_substringFromIndex:(NSUInteger)from
{
if (from < 0) {
return @"";
}
if (from >= self.length) {
return [self sj_substringFromIndex:from];
}
NSRange firstRange = [self rangeOfComposedCharacterSequenceAtIndex:from];
if (firstRange.location != from) {
return [self sj_substringFromIndex:(firstRange.location + firstRange.length)];
} else {
return [self sj_substringFromIndex:from];
}
}
同理,虽然没有发现substringToIndex:
越界会有什么影响,但是以防万一我们也优化下:
- (NSString *)sj_substringToIndex:(NSUInteger)to
{
if (to <= 0) {
return @"";
}
if (to > self.length) {
return [self jw_substringToIndex:to];
}
NSRange lastRange = [self rangeOfComposedCharacterSequenceAtIndex:to - 1];
if (lastRange.length > 1) {
return [self jw_substringToIndex:lastRange.location];
} else {
return [self jw_substringToIndex:to];
}
}
还有个问题,使用substringWithRange:
时,分类交换的方法并没有执行,也就是NSString
子类自己实现了substringWithRange:
,方法交换就不好用了,只能使用直接调用我们自己写的方法了。
rangeOfComposedCharacterSequencesForRange:
这个可以获取当前range
有效字符的所有range
写了两个方法,一个字符被截取时直接省略,一个只要包含字符一部分就选取整个字符
- (NSString *)sj_substringWithRange_validSub:(NSRange)range
{
if (range.length == 0 || range.location + range.length > self.length) {
return @"";
}
NSInteger loc = range.location;
NSInteger len = range.length;
NSRange firstRange = [self rangeOfComposedCharacterSequenceAtIndex:loc];
NSRange lastRange = [self rangeOfComposedCharacterSequenceAtIndex:loc + len - 1];
if (firstRange.location != loc) {
len -= (firstRange.location + firstRange.length - loc);
loc = firstRange.location + firstRange.length;
}
if (lastRange.length > 1 && (lastRange.location + lastRange.length) > loc + len) {
len = lastRange.location - loc;
}
if (len <= 0) {
return @"";
} else {
return [self substringWithRange:NSMakeRange(loc, len)];
}
}
- (NSString *)sj_substringWithRange_validAll:(NSRange)range
{
NSRange newRange = [self rangeOfComposedCharacterSequencesForRange:range];
return [self substringWithRange:newRange];
}
[图片上传失败...(image-b601e4-1657456976062)]
代码可以通过pod安装 pod 'SJSubstrFix'
最后再放个下载地址
喜欢的请给个小⭐️⭐️!!!
网友评论