Info

この質問は閉じられています。 編集または回答するには再度開いてください。

Reading a Text File

1 回表示 (過去 30 日間)
Bridgit Nata
Bridgit Nata 2016 年 11 月 19 日
閉鎖済み: MATLAB Answer Bot 2021 年 8 月 20 日
Hi,
I'm a bit lost with Input/Output and text files on MATLAB. If I'm given a text file containing a list of names and telephone numbers e.g.
John Smith 415 278 9082
Gabriel Zoro 214 678 0929
How can I create a function to search for a someone's first and last name and then display the line with the phone number?
Thank you!!
  2 件のコメント
Walter Roberson
Walter Roberson 2016 年 11 月 19 日
What do you know about the format of the file? Will each line always have exactly two names, separated by spaces? No "Dr", no middle names, no "Sr", no "von"?
Will each line always have exactly three portions of the phone number, separated by spaces? Does the phone number ever include '+' or '-' or '(' and ')' ?
Bridgit Nata
Bridgit Nata 2016 年 11 月 19 日
Each Line will have exactly two names separated by space - No "dr" middle names, titles etc.
The phone numbers doesn't always have three portions. But it always have a bracketed portion for the first part and separated by spaces between the portions. Some are like:
(415) 278 9082
(699) 987 6543
(011033-1) 3482152
(011-81-3) 34561212

回答 (1 件)

Walter Roberson
Walter Roberson 2016 年 11 月 19 日
searchfor = input('Name to look for?', 's');
fid = fopen('YourFile.txt', 'r');
matches = 0;
while true
thisline = fgetl(fid);
if ~ischar(thisline)
break; %end of file
end
if isempty( strtrim(thisline) )
continue; %just whitespace on this line
end
if strncmp( lower(thisline), lower(searchfor), length(searchfor))
matches = matches + 1;
fprintf('Match: %s\n', thisline);
end
end
if matches == 0
fprintf('No matches for "%s"\n', searchfor)
end

この質問は閉じられています。

Community Treasure Hunt

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

Start Hunting!

Translated by