フィルターのクリア

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 Center および File ExchangeCharacters and Strings についてさらに検索

タグ

製品

Community Treasure Hunt

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

Start Hunting!

Translated by