您好,登錄后才能下訂單哦!
TXT識別編碼是個復雜的問題。幸好有c/c++的一個庫能識別。
庫的叫uchardet,可以自己去github下載。但是沒有具體的使用手冊什么的。小研究了下 。
把uchardet文件夾下的.h和.cpp和.tab文件全部copy到自己的應用里面。然后在要自動識別編碼的地方
#include "uchardet.h"
如下代碼實現。
//
// EBOOKReadViewController.m
// EBOOk
//
// Created by 趙鋒 on 13-12-18.
// Copyright (c) 2013年趙鋒. All rights reserved.
//
#import "EBOOKReadViewController.h"
#include "uchardet.h"
#define NUMBER_OF_SAMPLES (2048)
@interfaceEBOOKReadViewController ()
{
constchar *encode;
}
@end
@implementation EBOOKReadViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [superinitWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
returnself;
}
- (void)viewDidLoad
{
[superviewDidLoad];
NSString *path=[[NSBundlemainBundle] pathForResource:@"五界至尊" ofType:@"txt"];
int result=[selfhaveTextBianMa:[path UTF8String]];
CFStringEncoding cfEncode = 0;
if (result==0) {
NSString *encodeStr=[[NSStringalloc] initWithCString:encodeencoding:NSUTF8StringEncoding];
if ([encodeStr isEqualToString:@"gb18030"]) {
cfEncode= kCFStringEncodingGB_18030_2000;
}elseif([encodeStr isEqualToString:@"Big5"]){
cfEncode= kCFStringEncodingBig5;
}elseif([encodeStr isEqualToString:@"UTF-8"]){
cfEncode= kCFStringEncodingUTF8;
}elseif([encodeStr isEqualToString:@"Shift_JIS"]){
cfEncode= kCFStringEncodingShiftJIS;
}elseif([encodeStr isEqualToString:@"windows-1252"]){
cfEncode= kCFStringEncodingWindowsLatin1;
}elseif([encodeStr isEqualToString:@"x-euc-tw"]){
cfEncode= kCFStringEncodingEUC_TW;
}elseif([encodeStr isEqualToString:@"EUC-KR"]){
cfEncode= kCFStringEncodingEUC_KR;
}elseif([encodeStr isEqualToString:@"EUC-JP"]){
cfEncode= kCFStringEncodingEUC_JP;
}
}
NSError *err;
NSString *str=[NSStringstringWithContentsOfFile:path encoding:CFStringConvertEncodingToNSStringEncoding(cfEncode) error:&err];
NSString *st=[str substringToIndex:1000];
self.txtView.text=st;
}
-(int)haveTextBianMa:(constchar*)strTxtPath{
FILE* file;
char buf[NUMBER_OF_SAMPLES];
size_t len;
uchardet_t ud;
/* 打開被檢測文本文件,并讀取一定數量的樣本字符 */
file = fopen(strTxtPath, "rt");
if (file==NULL) {
printf("文件打開失敗!\n");
return1;
}
len = fread(buf, sizeof(char), NUMBER_OF_SAMPLES, file);
fclose(file);
ud = uchardet_new();
if(uchardet_handle_data(ud, buf, len) != 0)
{
printf("分析編碼失敗!\n");
return -1;
}
uchardet_data_end(ud);
printf("文本的編碼方式是%s。\n", uchardet_get_charset(ud));
encode=uchardet_get_charset(ud);
uchardet_delete(ud);
return0;
}
- (void)didReceiveMemoryWarning
{
[superdidReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。