美文网首页
iOS从文件读取字符串,无分隔符分割成数组

iOS从文件读取字符串,无分隔符分割成数组

作者: 谭谭谭思密达 | 来源:发表于2022-03-31 15:30 被阅读0次

    iOS从文件读取中午使用UTF-8编码时,部分复杂的中文会占用4-6个字节。如果按1位来分割加入数组就会出现错误。如 𬺓 字,会占用两个长度。

        NSString *files  = [[NSBundle bundleWithPath:_bundlePath] pathForResource:@"cn_1.1" ofType:@"txt"];
        NSString *lines   = [[NSString stringWithContentsOfFile:files encoding:NSUTF8StringEncoding error:nil] stringByReplacingOccurrencesOfString:@"\n" withString:@""];
        NSMutableArray *characterArray = [NSMutableArray array];
        NSRange range = NSMakeRange(0, 1);
        for(int i = 0; i < lines.length; i += range.length){
            range.location = i;
            NSString *character = [lines substringWithRange:range];
            [characterArray addObject:character];
        }
    
    77695B33-126B-4E32-B8EC-C33FCC3CB780.png

    使用[str rangeOfComposedCharacterSequenceAtIndex:i]方法可以获得改文字的真实长度,用于分割可以得到正确的结果

        NSString *files  = [[NSBundle bundleWithPath:_bundlePath] pathForResource:@"cn_1.1" ofType:@"txt"];
        NSString *lines   = [[NSString stringWithContentsOfFile:files encoding:NSUTF8StringEncoding error:nil] stringByReplacingOccurrencesOfString:@"\n" withString:@""];
        NSMutableArray *characterArray = [NSMutableArray array];
        NSRange range = NSMakeRange(0, 1);
        for(int i = 0; i < lines.length; i += range.length){
            range = [lines rangeOfComposedCharacterSequenceAtIndex:i];
            NSString *character = [lines substringWithRange:range];
            [characterArray addObject:character];
        }
    

    相关文章

      网友评论

          本文标题:iOS从文件读取字符串,无分隔符分割成数组

          本文链接:https://www.haomeiwen.com/subject/czlnjrtx.html