【问题标题】:i need Insert spaces between a string in multi line text file matlab我需要在多行文本文件matlab中的字符串之间插入空格
【发布时间】:2017-08-31 21:24:16
【问题描述】:

我在文本文件中有这个字符串

 123456789
 987654321
 111111111
 222222222

如何在该文本文件中的每个数字之间插入 1 个空格?

为此:

1 2 3 4 5 6 7 8 9
9 8 7 6 5 4 3 2 1
1 1 1 1 1 1 1 1 1
2 2 2 2 2 2 2 2 2

【问题讨论】:

  • 在具有列编辑模式的编辑器(如 Notepad++)中打开文件,并在您想要的所有位置插入一列空格。不要用螺丝刀敲钉子。它需要很长时间并且会损坏螺丝刀。

标签: string matlab file text


【解决方案1】:
s=['123456789'
   '987654321'
   '111111111'
   '222222222'];    

s2=repmat(' ',size(s,1),2*size(s,2));
s2(:,1:2:end)=s

会给你

s2 =

1 2 3 4 5 6 7 8 9 
9 8 7 6 5 4 3 2 1 
1 1 1 1 1 1 1 1 1 
2 2 2 2 2 2 2 2 2 

更新:

使用dlmwrites 保存到空格分隔的文本文件中,如下所示:

 dlmwrite('testData.txt',s-'0',' ');

字符矩阵s 减去'0' 字符后转换为0-9 范围内的数值数组。请参阅 gnovice 的 solution 在同一文件中进行读取、处理和加载。

【讨论】:

    【解决方案2】:

    以下是读取、处理数据并将数据输出到同一文件的方法:

    fid = fopen('your_file.txt', 'r+');   % Open for both reading and writing
    data = fscanf(fid, '%c', Inf);        % Scan all contents into a character vector
    data = regexprep(data, '\S', '$0 ');  % Insert space after all non-whitespace
    fseek(fid, 0, -1);                    % Move file pointer to beginning of file
    fprintf(fid, '%c', data);             % Output data
    fclose(fid);                          % Close file
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-10-14
      • 2017-05-25
      • 2012-10-08
      • 1970-01-01
      • 1970-01-01
      • 2015-05-22
      • 2017-03-09
      相关资源
      最近更新 更多