Effacer les filtres
Effacer les filtres

strfind first occurrence.

104 vues (au cours des 30 derniers jours)
Pramit Biswas
Pramit Biswas le 19 Mai 2016
Commenté : Peter le 27 Sep 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;

Réponse acceptée

Guillaume
Guillaume le 19 Mai 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 commentaire
Peter
Peter le 27 Sep 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'.

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Characters and Strings dans Help Center et File Exchange

Tags

Produits

Community Treasure Hunt

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

Start Hunting!

Translated by