How can I find a character in a string?

조회 수: 27 (최근 30일)
Karis Anoruo
Karis Anoruo 2021년 7월 7일
댓글: Karis Anoruo 2021년 7월 12일
I am searching a textfile line by line for a particular character. Each line is being saved into a string format and then gets searched for the character. Written below is a section of the function I am using. None of the inbuilt string compare functions seem to be able to do this one task: find a character in a string and release the logical '1' if the character is there.
Am I missing a function? If not, how then do I do this please?
oneline = fgets(fid);
while ischar(oneline)
strncmp(character,oneline,strlength(oneline));
oneline = fgets(fid);
end
  댓글 수: 2
Stephen23
Stephen23 2021년 7월 7일
"Am I missing a function?"
The simplest one of all:
s = 'hello world';
x = s=='l'
x = 1×11 logical array
0 0 1 1 0 0 0 0 0 1 0
Karis Anoruo
Karis Anoruo 2021년 7월 12일
Thank you!

댓글을 달려면 로그인하십시오.

채택된 답변

Yongjian Feng
Yongjian Feng 2021년 7월 7일
ismember is the function you are looking for.

추가 답변 (1개)

Sulaymon Eshkabilov
Sulaymon Eshkabilov 2021년 7월 7일
Hi,
Here is one of the many possible solutions to your exercise:
clearvars
fid = fopen('TEXT__R.txt', 'r'); % Your text file
Letter = 'a'; % Looking for letter "a"
ii=1;
while 1
tline = fgetl(fid);
if ischar(tline)
fprintf('Searched line: %d \n', ii)
IDX =strfind(tline, Letter) % Index of "a" character location
N = numel(IDX);
fprintf('%5d "a" character was found \n', N) % Display the found results
ii=ii+1;
end
end
fclose(fid);

카테고리

Help CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by