【问题标题】:Separate chars of a file in matlab在matlab中分隔文件的字符
【发布时间】:2013-05-24 16:13:17
【问题描述】:

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

例如我有:

00000000000FDAD000DFD00ASD00

00000000000FDAD000DFD00ASD00

00000000000FDAD000DFD00ASD00

....

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

0000 0000 000F DAD0 00DF D00A SD00

0000 0000 000F DAD0 00DF D00A SD00

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

【问题讨论】:

  • 由于您已经为此工作了一段时间,请向我们展示您目前拥有的代码,并解释它不正确的地方。
  • 你有换行符分隔每一行吗?
  • 请注意,您的示例报告 28 个字符,而不是 32 个。

标签: string matlab chars


【解决方案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);

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

【讨论】:

  • 我特别喜欢(?!$)不匹配如果在最后!
【解决方案2】:

导入

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);

【讨论】:

    【解决方案3】:

    这是在 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);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-06-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多