NSString *str = @"????";NSRange range = NSMakeRange(2, str.length - 2);NSString *subStr = [str substringWithRange:range];
这里的str.length = 8,因为字符串是unicode格式,一个字符是4个字节组合表示的。
- (NSString *)utf8ToUnicode:(NSString *)string{ NSUInteger length = [string length]; NSMutableString *str = [NSMutableString stringWithCapacity:0]; for (int i = 0;i < length; i++){ NSMutableString *s = [NSMutableString stringWithCapacity:0]; unichar _char = [string characterAtIndex:i]; // 判断是否为英文和数字 if (_char <= '9' && _char >='0'){ [s appendFormat:@"%@",[string substringWithRange:NSMakeRange(i,1)]]; }else if(_char >='a' && _char <= 'z'){ [s appendFormat:@"%@",[string substringWithRange:NSMakeRange(i,1)]]; }else if(_char >='A' && _char <= 'Z') { [s appendFormat:@"%@",[string substringWithRange:NSMakeRange(i,1)]]; }else{ // 中文和字符 [s appendFormat:@"\\u%x",[string characterAtIndex:i]]; // 不足位数补0 否则解码不成功 if (s.length == 4) { [s insertString:@"00" atIndex:2]; } else if (s.length == 5) { [s insertString:@"0" atIndex:2]; } } [str appendFormat:@"%@", s]; } return str;}
NSString *strB = [self utf8ToUnicode:str];
将中文转成unicode形式,strB = @"\ud83d\udc74\ud83c\udffb\ud83d\udc6e\ud83c\udffd";
那subStr=@"\ud83c\udffb\ud83d\udc6e\ud83c\udffd";但是因为被截断后,打印出来变成了???,而如果range.location从1开始,出现都是unicode形式的字符串,因为被截断后没有对应的组合字符串可以显示。可以利用循环打印下结果
for (int i = 0; i < str.length; i++) { NSRange range = NSMakeRange(i, str.length - i); NSString *temp = [str substringWithRange:range]; NSLog(@"temp = %@", temp);}/* temp = ???? temp = \udc74\ud83c\udffb\ud83d\udc6e\ud83c\udffd temp = ??? temp = \udffb\ud83d\udc6e\ud83c\udffd temp = ?? temp = \udc6e\ud83c\udffd temp = ? temp = \udffd*/
结果可能不是我们想要的,我们如果想要截断后的字符为显示字符的子集,也就是??或??或者????。那么可以使用
rangeOfComposedCharacterSequencesForRange:调整range,防止有效的unicode字符被截断成无效字符(无显示意义)。请看下面
for (int i = 0; i < str.length; i++) { NSRange range = NSMakeRange(i, str.length - i); range = [str rangeOfComposedCharacterSequencesForRange:range]; NSString *temp = [str substringWithRange:range]; NSLog(@"temp = %@", temp);}/* temp = ???? temp = ???? temp = ???? temp = ???? temp = ?? temp = ?? temp = ?? temp = ??*/