Octave - 返回单元格数组中第一次出现字符串的位置

时间:2016-04-28 14:55:11

标签: string matlab octave string-search

Octave中是否有一个函数返回单元数组中第一次出现字符串的位置?

我找到了findstr,但这会返回一个我不想要的向量。我想要index做什么,但它只适用于字符串。

如果没有这样的功能,有没有关于如何去做的提示?

1 个答案:

答案 0 :(得分:6)

由于findstr已弃用,findstrcmpi的组合可能会很有用。 strcmpi通过忽略可能对您的目的有用的字母大小写来比较字符串。如果这不是您想要的,请使用不带尾随i的函数,因此strcmpstrcmpistrcmp的输入是搜索str的字符串,对于您的情况,附加输入参数是要搜索的字符串的单元数组A。输出strcmpistrcmp会为您提供logical值的向量,其中每个位置k会告诉您单元格数组k中的字符串A是否为strfind匹配。然后,您可以使用n查找字符串匹配位置的所有位置,但您可以通过指定最大位置数n以及约束搜索位置来进一步限制它 - 特别是如果您需要查看字符串匹配的第一个或最后str个位置。

如果所需的字符串位于A且您的单元格数组存储在index = find(strcmpi(str, A)), 1, 'first'); 中,只需执行以下操作:

find

重申一下,octave:8> A = {'hello', 'hello', 'how', 'how', 'are', 'you'}; octave:9> str = 'hello'; octave:10> index = find(strcmpi(str, A), 1, 'first') index = 1 octave:11> str = 'goodbye'; octave:12> index = find(strcmpi(str, A), 1, 'first') index = [](1x0) 将找到字符串匹配的所有位置,而第二个和第三个参数告诉您仅返回结果的第一个索引。具体来说,这将返回所需搜索字符串的第一次出现,如果找不到则返回空数组。

运行示例

let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let vc = storyboard.instantiateViewControllerWithIdentifier("MyTableViewController") as! MyTableViewController
        vc.myObject = object // I pass some data
        presentViewController(vc, animated: true, completion: nil) 
相关问题