printing full stop in next line

2 views (last 30 days)
libra
libra on 1 Mar 2018
Commented: Jan on 2 Mar 2018
fid1=fopen('prompts2','r');
fid2=fopen('prompts3trialtimitsmall','w');
while ~ feof(fid1)
new_line = fgetl(fid1);
a=new_line;
b=strsplit(a);
c=[b(end) b];
c(end)=[];
c=c;
fprintf(fid2, '%s\n', c {:})
end
fclose(fid1);
fclose(fid2);
my sentences in prompts2 are like this Alfalfa is healthy for you. */sx21 sentences in output file is
*/sx21
Alfalfa
is
healthy
for
you.
I want
*/sx21
Alfalfa
is
healthy
for
you
.
i.e. last full stop to print in next line I have tried converting z= char(c(end)) and then printing but not succed.

Answers (1)

Jan
Jan on 1 Mar 2018
Edited: Jan on 2 Mar 2018
Replace:
fprintf(fid2, '%s\n', c {:})
by
str = sprintf('%s\n', c {:});
str = strrep(str, '.', [char(10), '.']); % [EDITED, typo fixed]
fprintf(fid2, '%s', str);
  3 Comments
libra
libra on 2 Mar 2018
Edited: per isakson on 2 Mar 2018
completed myself by simple programming
b=strsplit(a);c=[b(end) b];
c=cat(2,b(end),b);
c(end)=[];
c=c(1:end);
k=c(end);
l=char(c(end));
l(end)=[];
l=l
d=vertcat(c','.')
g=d(end-1);
h=char(g);
h(end)=[];
h=h;
s=d(end-1);
j=strrep(d,s,h)
fprintf(fid2, '%s\n', j{:})
by changing in above code
Jan
Jan on 2 Mar 2018
also I have tried many different options with strrep but not worked
Yes, I had a typo in my code. Replace
str = strrep('.', [char(10), '.']);
by
str = strrep(str, '.', [char(10), '.']);
Using the curly braces to access a cell element is more efficient than creating a scalar cell at first and converting it by char:
% l=char(c(end))
l = c{end}; % Much better and nicer
This is not meaningful:
h=h;
% or
c=c;
This is simply a waste of time and confuses the readers. This is cluttering also:
new_line = fgetl(fid1);
a=new_line;
What about:
a = fgetl(fid1)
?
This does the same thing twice, so omit one of the lines:
c=[b(end) b];
c=cat(2,b(end),b);
This is not used anywhere, to better remove it:
k=c(end);
Finally let me summary my suggestion with your original (much clearer) code:
fid1 = fopen('prompts2','r');
fid2 = fopen('prompts3trialtimitsmall','w');
while ~ feof(fid1)
a = fgetl(fid1);
b = strsplit(a);
c = [b(end), b(1:end-1)];
str = sprintf('%s\n', c{:});
str = strrep(str, '.', [char(10), '.']);
fwrite(fid2, str, 'char'); % Faster than FPRINTF
end
fclose(fid1);
fclose(fid2);

Sign in to comment.

Categories

Find more on Scripts 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!