0

我在一个文件中有 32 个字符的字符串(多行)。我想要做的是制作一个新文件,并通过每列 4 个字符将它们放在那里。

例如我有:

00000000000FDAD000DFD00ASD00

00000000000FDAD000DFD00ASD00

00000000000FDAD000DFD00ASD00

....

在新文件中,我希望它们看起来像这样:

0000 0000 000F DAD0 00DF D00A SD00

0000 0000 000F DAD0 00DF D00A SD00

你有人能帮帮我吗?我现在工作了几个小时,但找不到解决方案。

4

3 回答 3

1

首先,打开输入文件并将这些行作为字符串读取:

infid = fopen(infilename, 'r');
C = textscan(infid, '%s', 'delimiter', '');
fclose(infid);

然后用于regexprep将字符串拆分为以空格分隔的 4 个字符组:

C = regexprep(C{:}, '(.{4})(?!$)', '$1 ');

最后,将修改后的行写入输出文件:

outfid = fopen(outfilename, 'w');
fprintf(outfid, '%s\n', C{:});
fclose(outfid);

请注意,此解决方案足够强大,可以处理可变长度的行。

于 2013-05-24T23:54:34.547 回答
0

这是在 Matlab 中执行此操作的一种方法:

% read in file
fid = fopen('data10.txt');
data = textscan(fid,'%s');
fclose(fid);

% save new file
s = size(data{1});
newFid = fopen('newFile.txt','wt');
for t = 1:s(1) % format and save each row
    line = data{1}{t};
    newLine = '';
    index = 1;
    for k = 1:7 % seven sets of 4 characters
        count = 0;
        while count < 4
            newLine(end + 1) = line(index);
            index = index + 1;
            count = count + 1;
        end
        newLine(end + 1) = ' ';
    end
    fprintf(newFid, '%s\n', newLine);
end
fclose(newFid);
于 2013-05-24T17:55:56.947 回答
0

进口

fid = fopen('test.txt');
txt = textscan(fid,'%s');
fclose(fid);

转换为 M x 28 字符数组,转置和重塑以在每列上有一个 4 字符块。然后在底部添加一排空白并重新整形。将每一行存储在一个单元格中。

txt = reshape(char(txt{:})',4,[]);
txt = cellstr(reshape([txt; repmat(' ',1,size(txt,2))],35,[])')

将每个单元格/行写入新文件

fid = fopen('test2.txt','w');
fprintf(fid,'%s\r\n',txt{:});
fclose(fid);
于 2013-05-24T19:47:23.223 回答