Write a function called digit_counter that takes the name of a text file as input and returns the number of digits (i.e., any of the characters, 0-to-9) that the file contains. If there is a problem opening the file, the function returns -1

1 回表示 (過去 30 日間)
function[c]=digit_counter(filename)
fid=fopen(filename,'rt');
if fid<0
error('error opening file %s', filename);
end
A = char(fread(fid,inf)).';
c=length(A);
fclose(fid);
end

回答 (2 件)

Walter Roberson
Walter Roberson 2016 年 9 月 23 日
Your code returns the number of bytes in the file. The requirements are that it return the number of digits in the file -- that is, the total number of occurrences of any of the characters '0', '1', '2', '3', '4', '5', '6', '7', '8', or '9'
  2 件のコメント
Kapil Dhanwani
Kapil Dhanwani 2016 年 9 月 23 日
Yes I want digits only...no alphabets and no space so what changes I should make
Walter Roberson
Walter Roberson 2016 年 9 月 23 日
Hint:
if A(idx) == '0'
digit0 = digit0 + 1;
elseif ....

サインインしてコメントする。


Srishti Saha
Srishti Saha 2018 年 5 月 13 日
A simple function as this would work:
function n = digit_counter(fname)
n = -1;
fid = fopen(fname,'r');
if fid >= 0
n = sum(isstrprop(fread(fid,inf,'char=>char'),'digit'));
fclose(fid);
end
end

カテゴリ

Help Center および File ExchangeFunction Creation についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by