Write sections of a long string as new lines in a text document

4 views (last 30 days)
David Haydock
David Haydock on 18 Jan 2022
Answered: Steven Lord on 18 Jan 2022
I have a very long string value, approx. 13,000 characters long, that is made up of the letters X, Y and Z. So:
sub = 'XYZYXYZYZYZXYZYXYZ....'
and so on. Within the long string, there is also every so often a 0:
sub = '...X0Y...'
The 0 represents a break point. I need to write out this long sequence onto a single txt file, but at each instance where there is a '0', I need to remove that zero and start a new line on the text file.
How would I go about doing this?

Accepted Answer

Stephen23
Stephen23 on 18 Jan 2022
sub = 'XYZYXYZYZYZXYZYXYZ0XYXYXYX';
tmp = split(sub,'0');
fprintf('%s\n',tmp{:})
XYZYXYZYZYZXYZYXYZ XYXYXYX
  1 Comment
Stephen23
Stephen23 on 18 Jan 2022
Where of course you replace that FPRINTF line with:
fid = fopen('myfile.txt','wt');
fprintf(fid,'%s\n',tmp{:});
fclose(fid);

Sign in to comment.

More Answers (1)

Steven Lord
Steven Lord on 18 Jan 2022
sub = 'XYZYXYZYZYZXYZYXYZ0XYXYXYX';
sub2 = replace(sub, '0', newline)
sub2 =
'XYZYXYZYZYZXYZYXYZ XYXYXYX'

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!