MATLAB Answers

How do I find the number of character in a text file?

89 ビュー (過去 30 日間)
raktim banerjee
raktim banerjee 2011 年 1 月 26 日
I have a text file 'inp.txt' containing one line like this:
'banerjee.raktim 123456789125'
I want to know the number of character present in this line, including the white space. And also want to know the position of the white space character.
The expected no of character is 28 and opsition of space is:
How to do this?


Matt Fig
Matt Fig 2011 年 1 月 26 日
fid = fopen('inp.txt'); % see also fclose
A = char(fread(fid,inf)).';
A =
banerjee.raktim 123456789125
>> length(A)
ans =
>> strfind(A,' ')
ans =
  3 件のコメント
Jan 2011 年 1 月 26 日
This "A = char(fread(fid,inf)).';" is can be improved: "A = fread(fid, [1, inf], '*char');" This avoid a data copy, casting and transpose operation, but creates a tiny [1x2] vector. But FGETL is efficient also and available in Matlab 6.5.


その他の回答 (2 件)

Walter Roberson
Walter Roberson 2011 年 1 月 26 日
Are the quote marks and the period present in the file? For the purposes of this discussion I will presume they are not.
a = textread('inp.txt','%s','Whitespace','');
line_length = length(a{1});
space_pos = find(a{1} == ' ',1,'first');
fprintf('The actual number of characters was %d and the actual space position was %d', line_length, space_pos);
  5 件のコメント
Jan 2011 年 1 月 26 日
TEXTREAD is available in Matlab 6.5, but you have to use lower case for 'whitespace'.


Gary 2011 年 1 月 26 日
for a text file, doesn't each character represent 1 byte?
Does the 'dir' function exist in Matlab 6.5? In my tests creating a text file in Windows notepad, then getting the file size using Matlab's 'dir', the reported number of bytes in the file is equal to the number of characters I typed into it.
Of course, that doesn't tell you where the spaces are.
  6 件のコメント
Walter Roberson
Walter Roberson 2011 年 1 月 28 日
Gary, MS Windows is happy to write UTF-16 text files, so we cannot count on one character being the same as 1 byte, even without these issues of line or file terminators.


Community Treasure Hunt

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

Start Hunting!

Translated by