필터 지우기
필터 지우기

strfind first occurrence.

조회 수: 104 (최근 30일)
Pramit Biswas
Pramit Biswas 2016년 5월 19일
댓글: Peter 2019년 9월 27일
str = 'Find the starting indices of a pattern in a character vector'; k = strfind(str,'in') gives, k = 2 15 19 40
any shortcut/direct way to get the first occurrence only. Here in this case: k = 2;

채택된 답변

Guillaume
Guillaume 2016년 5월 19일
You could use regexp with the 'once' option:
k = regexp(str, 'in', 'once')
However, note that some characters have special meanings in regular expression, so if your search string is completely arbitrary you can't just replace strfind with regexp. For safety you can regexptranslate the search string.
On the other hand, what's stopping you from writing:
k = strfind(str, 'in); k = k(1);
If writing two instructions instead of one bother you, you can always create your own function:
function location = strfindfirst(lookin, lookfor)
location = strfind(lookin, lookfor);
if ~isempty(idx)
location = location(1);
end
end
  댓글 수: 1
Peter
Peter 2019년 9월 27일
While the suggested answer works, it is inefficient. If you have very long strings to search through and/or have many strings to search, finding all of the occurances first, and then truncating the answer to just to first one, is a waste. Its too bad that strfind doesn't have a 'first' or 'last' option like 'find'.

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

추가 답변 (0개)

카테고리

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