Search for a specific string in a vector (Octave)

I am trying to find a string in a vector. For example: query = "ab" in vector = ["ab", "cd", "abc", "cab"]

The problem is that it gives all indexes that have the string "ab" when I use the strfind (vector, query) function. In this case, "ab", including "abc" and "cab". But I want only the index "ab" and not others. Is there any specific function for this in Octave?

+7
string-matching octave
source share
1 answer

The problem is your syntax. When you execute vector = ["ab", "cd", "abc", "cab"] , you do not create a vector of these several lines, you combine them into one line. What you need to do is create an array of row cells:

 vector = {"ab", "cd", "abc", "cab"}; 

And then you can do:

 octave-cli-3.8.2> strcmp (vector, "ab") ans = 1 0 0 0 

Many other functions will work correctly with an array of row cells, including strfind , which in this case gives you the indices in each cell where the string "ab" is:

 octave-cli-3.8.2> strfind (vector, "ab") ans = { [1,1] = 1 [1,2] = [](0x0) [1,3] = 1 [1,4] = 2 } 
+6
source share

All Articles