Search a particular string in a vector(Octave)

user3713665 picture user3713665 · Sep 4, 2014 · Viewed 7.9k times · Source

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

The problem is: It is giving all the indices which have string "ab" when I use the function strfind(vector,query). In this case "ab" including "abc" and "cab". But i only want the index of "ab" not others. Is there any specific function for this in Octave?

Answer

carandraug picture carandraug · Sep 4, 2014

The problem is on your syntax. When you do vector = ["ab", "cd", "abc", "cab"], you are not creating a vector of those multiple strings, you are concatenating them into a single string. What you should do is create a cell array of strings:

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 cell array of strings, including strfind which in this cases gives you the indices on each cell where the string "ab" stars:

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