strfind first occurrence.

105 visualizzazioni (ultimi 30 giorni)
Pramit Biswas
Pramit Biswas il 19 Mag 2016
Commentato: Peter il 27 Set 2019
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;

Risposta accettata

Guillaume
Guillaume il 19 Mag 2016
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 Commento
Peter
Peter il 27 Set 2019
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'.

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su Characters and Strings in Help Center e File Exchange

Tag

Prodotti

Community Treasure Hunt

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

Start Hunting!

Translated by