Search code examples
arraysstringoctave

Octave - Adding '\n' to String Array is Not Creating a New Line


I want to change ',' character to '\n' and save it to the text file

All files are in this format:

546,234,453,685,.....,234

I want to make it like:

546

234

453

685

...

234

My initiation to this problem is like this:

fid=fopen(files{i});
strArr=fscanf(fid,'%s');

newstrArr=strrep(strArr,',','\n');

% Take each .txt input
for j=1:length(newstrArr)  
   Array=[Array newstrArr(j)];   
endfor

Let me explain step by step:

1st I open the current text file

 fid=fopen(files{i});

2nd I find the strings in text file

strArr=fscanf(fid,'%s');

Please Note that you can't replace %s with %d. (Correct me if I am wrong)

3rd I replace commas with newline character

newstrArr=strrep(strArr,',','\n');

4th I add each character to a new array with for loop

for j=1:length(newstrArr)  
   Array=[Array newstrArr(j)];   
endfor

However When I display, using;

disp(Array);

I have this output

How can I properly replace the commas with newlines?

Regards


Solution

  • The issue is that you are inserting a literal '\n' (the characters \ and n) and not a newline character. This is because in Octave, a single-quote enclosed string ignores escape sequences. If you want Octave to respect escape sequences you could use a double-quoted string which will convert \n into a newline.

    strrep(strArr, ',', "\n");
    

    Or if you want your code to be MATLAB-compatible, you'll want to instead use char(10) (an actual new-line character). This is because MATLAB does not have double-quote enclosed strings.

    output = strrep(strArr, ',', char(10));
    

    Another option would be to split your input at the , and use sprintf to add the newlines (it'll treat \n as a newline)

    values = strsplit(strArr, ',');
    output = sprintf('%s\n', values{:});
    

    If you just want to save each entry to a new line in a file, you can use fprintf instead.

    values = strsplit(strArr, ',');
    fout = fopen('output.txt', 'w');
    fprintf(foug, '%s\n', values{:});
    fclose(fout);