How do i change my script to print out the second word of each even line?

6 vues (au cours des 30 derniers jours)
Davifus
Davifus le 7 Nov 2019
Commenté : Adam Danz le 7 Nov 2019
fn = input( 'file name: ', 's' );
fh = fopen( fn, 'r' );
ln = '';
count=1;
while ischar( ln )
ln = fgets( fh );
if (ischar( ln ) && mod(count,2)==0)
fprintf( ln );
end
count=count+1;
end
fclose( fh );
I created a script that prints out the even line of a input file but i dont know how to make it print out the second word of each even line.

Réponse acceptée

Adam Danz
Adam Danz le 7 Nov 2019
Modifié(e) : Adam Danz le 7 Nov 2019
Instead of reading the file line by line you could read in the entire text file and then extract the 2nd word from even numbered lines of the text with just 3 lines of code.
% Read entire file as a char array
C = fileread('MyTextFile.txt');
% Split the char array by line and then split by word.
% ca{j}{m} is the m_th word in the j_th line of text.
ca = cellfun(@strsplit,strtrim(strsplit(C, newline())),'UniformOutput',false);
% get 2nd word of each even numbered line unless the line only has 1 word.
% If the line is empty, it will return an empty.
words = cellfun(@(s)s{min(numel(s),2)},ca(2:2:end),'UniformOutput',false);
% [1]^ [2]^^^^^^^^
% [1] get 2nd word
% [2] isolate even-numbered lines
If you'd rather maintain your fgets method, add the two lines below to display the 2nd word of ln unless it only has 1 word in which case it displays the first word.
lnSplit = strsplit(ln);
fprintf('%s\n',lnSplit{min(numel(lnSplit),2)})
% ^^ Assuming you want a line break
  6 commentaires
Davifus
Davifus le 7 Nov 2019
thank you it works.
Adam Danz
Adam Danz le 7 Nov 2019
Great! Glad I could help.

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Text Data Preparation dans Help Center et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by