How to Differentiate between '\n' and CR/LF when reading in text files in MATLAB

20 ビュー (過去 30 日間)
akazakov
akazakov 2016 年 7 月 20 日
回答済み: akazakov 2016 年 7 月 20 日
I am trying to read in a text file where each row contains a string. Some rows contain the character combination '\n' and '\r', and then all rows end with a CR and LF marker (I opened the file in Notepad++ to see this). For example:
First Name
Birthdate
Average\nLength
Avoid\rWater
...and so on.
The issue is that when I use textscan and set either '\n' or '\r' as the delimiter, MATLAB parses the incoming file at every '\n' or '\r' and CR or LF, where I need to only have actual carriage returns and line feeds break the line. Is there some sort of identifier I can use to differentiate a CR/LF from '\n' and '\r'?
fid=fopen('text.txt', 'r+');
full=textscan(fid, '%s', 'Delimiter', '\n') % I tried with '\r' as delimiter as well, and the result is the same
printFile=fopen('results.txt', 'at');
for i=1:length(full{1})
str=full{1}{i};
str=strrep(str, '\n', '$'); % I need to input a '$' as a manual delimiter in place of actual CR and LF.
% However this will replace both '\n' *and* CR/LF with '$'.
fprintf(printFile, '%s$', str);
end
fclose all;

採用された回答

akazakov
akazakov 2016 年 7 月 20 日
I've been sitting with this problem for a while, and the second I posted a question I figured it out :)
a=sprintf('\n') % a now equals a line feed
b=sprintf('\r') % b now equals a carriage return
Using these as delimiters directly solves my problem. So given my original sample code:
fid=fopen('text.txt', 'r+');
full=textscan(fid, '%s', 'Delimiter', sprintf('\r'));
fclose all;
% This reads in the text file, creating a new line at every carriage return
% and doing nothing when it sees a '\n' or '\r'

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeCharacters and Strings についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by