如何在 MATLAB 的列表框中正确显示带有制表符的文本

How to properly display text with tabs in listbox in MATLAB

我正在将文件中的文本插入到我的列表框中,但它忽略了字符串之间的制表符。我怎样才能让它不忽略标签并按原样打印?

我的文本文件:

05-WD-3052      19:56:07        03-Apr-2016
06-C-874414     19:57:03        03-Apr-2016
10-G-11         19:58:03        03-Apr-2016

列表框中的结果

我的代码:

fileID = fopen('Output/LicenseLog.txt','rt');
tScan = textscan(fileID, '%s','Delimiter','');
newScan = tScan{:};
set(handles.listbox1,'String',newScan);
fclose(fileID);

列表框符合您输入中的制表符,但您使用的是可变宽度字体,因此文本没有像您期望的那样排列。您可以更改您选择的 FontName property of your listbox to 'FixedWidth' to use the default fixed-width font or you can set it to any fixed-width/monospaced font 以获得预期结果:

data = {'05-WD-3052     19:56:07     03-Apr-2016', ...
        '06-C-874414    19:57:03     03-Apr-2016', ...
        '10-G-11        19:58:03     03-Apr-2016'};

u = uicontrol('Style', 'list', ...
              'FontName', 'FixedWidth', ...
              'String', data);

更新

仔细查看您的数据后,问题是选项卡在多个系统、程序等中的显示方式不同。您的某些行实际上需要 两个 选项卡以在您的 GUI 中查看时正确对齐所有内容。因此,您可能希望使用 sprintf 将制表符分隔的列表转换为具有显式空格的列表。

%// Split the string into groups based on the tabs
pieces = regexp(tScans{1}, '\t+', 'split');
for k = 1:numel(pieces)
    %// Create a 20-character wide padded string for each element
    data{k} = sprintf('%-20s', pieces{k}{:})
end

set(handles.listbox, 'String', data)

或者如果你想要一个单线:

data = cellfun(@(x)sprintf('%-20s', x{:}), regexp(tScan{1}, '\t+', 'split'), 'uni', 0);
set(handles.listbox, 'String', data)

将它与上面提到的固定宽度字体结合使用时,您应该会得到想要的行为。