matlab字符串与希腊字符

时间:2014-04-01 11:21:14

标签: string matlab

是否可以比较完全用希腊字符书写的字符串? 例如:

str1='ΑΒΓΔ'
str2='ΕΖΗΘ'
strcmp(str1,str2)

当我从文件中读取希腊字符串时,是否可以应用上述内容? 例如:

line='ΑΒΓΔ;ΕΖΗΘ'
[str1 str2] = strread(line,'%s %s','delimiter',';')
strcmp(str1,str2)

2 个答案:

答案 0 :(得分:2)

MATLAB和unicode 仍然尚未好好混合,AFAIK。你的第一个例子遗憾地返回误报。你的第二个例子是有效的,但并非没有它的警告。

test.txt为例(使用UTF-8编码):

ΑΒΓΔ;ΕΖΗΘ

然后:

%// First try: 
fid = fopen('test.txt', 'r', 'n', 'UTF-8');
A = textscan(fid, '%s', 'delimiter', ';');
fclose(fid);
A{1}{1}+0
%// apparently, textscan does not read the correct number of bits per
%// character...


%// Let's try manually:
fid = fopen('test.txt', 'r', 'n', 'UTF-8');
txt = fgetl(fid);
fclose(fid);

%// That makes things even worse! All characters get converted to the
%// placeholder character 26, causing false positives in string
%// comparisons:
D = textscan(txt, '%s', 'delimiter', ';');
D{1}{1}+0
strcmp(D{1}{2}, D{1}{2})


%// Regexp works better; it preserves the right character codes and yields
%// a (correct) negative on comparison:
C = regexp(txt, ';', 'split');
C{1}+0
strcmp(C{1}, C{2})


%// So, the "best" way: 
fid = fopen('test.txt', 'r', 'n', 'UTF-8');
D   = {};
while ~feof(fid)
    line     = fgetl(fid);
    D{end+1} = regexp(line, ';', 'split'); %#ok<SAGROW>
end
fclose(fid);

除非您为支持unicode的命令窗口/编辑器窗口专门选择了字体,否则disp仍然无法正确显示它们。

如果您使用Linux,如果您从bash或类似地方调用MATLAB,则unicode显示正常。但这与你的shell有关,而不是MATLAB ......

另外,查看help unicode2native

%// Reading
fid = fopen('japanese.txt', 'r', 'n', 'Shift_JIS');
str = fread(fid, '*char')';
fclose(fid);

disp(str);

%// Writing
fid = fopen('japanese_out.txt', 'w', 'n', 'Shift_JIS');
fwrite(fid, str, 'char');
fclose(fid);

disp在这里进行了故障转移(R2010a),但写入正常......

答案 1 :(得分:0)

字符串编码不是MATLAB的优点之一。对于使用Unicode,有unicode2nativenative2unicode。但是,就我所知,您在代码中输入的字符串文字仅为ASCII。这意味着您需要使用fread从使用合适编码的文件中读取非ASCII字符串,然后使用native2unicode将原始字节转换为Unicode。

相关问题