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

1 visualización (últimos 30 días)
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.

Respuesta aceptada

Adam Danz
Adam Danz el 7 de Nov. de 2019
Editada: Adam Danz el 7 de Nov. de 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 comentarios

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Text Data Preparation en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by