How do I detect a "tab" character in a line of text read by fgetl?

조회 수: 51 (최근 30일)
Clay Fulcher
Clay Fulcher 2020년 5월 21일
답변: Clay Fulcher 2020년 5월 22일
I am using fgetl to read lines in a text file. Is there a way to detect whether one of the whitespace characters is a "tab" ?
Thanks in advance for your help.

채택된 답변

dpb
dpb 2020년 5월 21일
l=fgetl(fid);
istab=(l==9); % the fast way...
%
istab=strfind(l,char(9)); % the char() string string functions way

추가 답변 (2개)

Walter Roberson
Walter Roberson 2020년 5월 21일
S = sprintf('abc\tdef'); %text with a tab in it
S == 9 %fast, simple, and tab character unlikely to change any year soon
strfind(S, sprintf('\t')) %just in case tab someday changes to a multi-character sequence
%unicode defines three additional tab-related functions
ismember(S, [0x09 0x0b 0x88 0x89 0x8a]) %HT VT CTS CTJ LTS
%unicode defines several tab symbols
ismemember(S, [0x09 0x0b 0x88 0x89 0x8a 0x2409 0x240b 0x21b9 0x21c6 0x21E4 0x21E5]) %HT VT CTS CTJ LTS various tab symbols

Clay Fulcher
Clay Fulcher 2020년 5월 22일
Thanks to Walter Roberson and dpb for the help above. Here is the new "tab detector!"
function [x, tabpositions] = istab(line)
%
% This function detects any "tab" characters in a character string and
% returns logical TRUE if tabs are present, or logical FALSE if tabs are
% not present. Optionally returns the positions of the tab(s) in the line.
%
% USAGE
% [x,tabpositions]=istab(line)
%
% INPUT
% line - [1 x n] character string with or without tabs
%
% OUTPUT
% x - logical TRUE or FALSE indicating presence of tab(s) in line.
% tabpositions - [1 x ntabs] vector showing positions of tabs in line.
%
% line must be a character string or empty
if ~ischar(line) & ~isempty(line)
disp(' ')
disp(' Input must be a character string.')
return
end
% line must contain only one line
if size(line,1)>1
disp(' ')
error(' Character string must be no more than one line.' )
return
end
% Put logical 1 where tab exists, logical 0 where it does not in string.
% Could use x=(line==9), but the following eliminates the case where this
% designator for the tab character is changed in the future.
x=(line==sprintf('\t'));
% Find the positions in line where tabs exist.
tabpositions=find(x);
if isempty(tabpositions), tabpositions=[]; end
% Return only logical 1 or 0, however many tabs there are in line.
x=x(find(x));
if ~isempty(x), x=x(1); end
if isempty(x), x=logical(0); end
% Display the logical result for tab existence.
if x, 1==1, end
if ~x, 1==2, end
return

카테고리

Help CenterFile Exchange에서 Text Data Preparation에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by