If the file is not found or the character is not a valid char, the function should return a value -1.
1 次查看(过去 30 天)
显示 更早的评论
I am creating a function that counts the given character present in the text file. Problem I am facing is if the text file is not found the function should return value -1 and also if the given character is not a valid one it should return -1.
function [charnum]=char_counter(fname,character)
fid=fopen(fname,'rt')
if fid<0 || ischar(character)==0
charnum=-1;
else
str=fileread(fname);
if strncmpi(character,str,inf)==0
charnum=-1;
end
charnum=count(str,character);
end
0 个评论
采纳的回答
David Hill
2020-4-18
How are you defining a valid character? You can use try,catch.
function [charnum]=char_counter(fname,character)
try fid=fopen(fname,'rt');
catch
charnum=-1;
return;
end
if fid<0 || ischar(character)==0
charnum=-1;
else
str=fileread(fname);
if strncmpi(character,str,inf)==0
charnum=-1;
end
charnum=count(str,character);
end
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Cell Arrays 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!