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?
k = strfind( str , pat ) searches str for occurrences of pat . The output, k , indicates the starting index of each occurrence of pat in str . If pat is not found, then strfind returns an empty array, [] . The strfind function executes a case-sensitive search.
To determine if two strings are identical it is necessary to use the strcmp function. It compares complete strings and is case sensitive. strncmp compares only the first N characters (with N given as a parameter). strcmpi and strncmpi are the corresponding functions for case-insensitive comparison.
You can index into, reshape, and concatenate string arrays using standard array operations, and you can append text to them using the + operator.
To obtain a single index for each matrix element, Octave pretends that the columns of a matrix form one long vector (like Fortran arrays are stored). For example: find (eye (2)) ⇒ [ 1; 4 ] If two inputs are given, n indicates the maximum number of elements to find from the beginning of the matrix or vector.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With