How do I create a new line after every 3 characters in a text file?
Show older comments
If I had a .txt file that has one line as
abcdefghijklmnopqrstuvwxyz
I would like either to change or create a new .txt file that would look like this:
abc
def
ghi
jkl
mno
pqr
stu
vwx
yz
So, it's essentially reading 3 characters from the right, creating a new line '\n', going to the second line, reading 3 characters, creating a new line, etc.
Thank you!
Answers (1)
ES
on 23 Jan 2014
fileID=fopen('InputFile.txt','r');
AllText = fscanf(fileID, '%s')
TextLength=length(AllText);
NoOfLines=ceil(TextLength/3);
OutFileID=fopen('OutputFile.txt','w');
for l1=0:NoOfLines
try
SrcString=AllText((l1*3)+1:(l1*3)+3)
catch
SrcString=AllText((l1*3)+1:end)
end
fprintf(OutFileID,'%s\r\n',SrcString);
end
Categories
Find more on String Parsing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!