String 具有线性时间查找的字符串数组

String 具有线性时间查找的字符串数组,string,matlab,data-structures,String,Matlab,Data Structures,我在Matlab中进行字符串处理,我通常使用单元格数组在文本中存储单个单词 例如: a = {'this', 'is', 'an', 'array', 'of', 'strings'} 为了在这个数组中搜索单词“of”,我在数组中循环并对照我的单词检查每个元素。这种方法不能扩展,因为如果我得到一个大的数据集,我的数组a会变大,循环元素是不明智的。我想知道是否有更聪明的方法,也许是Matlab中更好的本机数据结构,可以帮助我更快地运行它?a是一种选择。我不知道您打算执行哪种特定类型的字符串处理,

我在Matlab中进行字符串处理,我通常使用单元格数组在文本中存储单个单词

例如:

a = {'this', 'is', 'an', 'array', 'of', 'strings'}
为了在这个数组中搜索单词“of”,我在数组中循环并对照我的单词检查每个元素。这种方法不能扩展,因为如果我得到一个大的数据集,我的数组a会变大,循环元素是不明智的。我想知道是否有更聪明的方法,也许是Matlab中更好的本机数据结构,可以帮助我更快地运行它?

a是一种选择。我不知道您打算执行哪种特定类型的字符串处理,但下面是一个示例,说明如何将每个字符串存储为一个键,该键与该单词在单元格数组中的索引位置向量相关联:

a = {'this', 'is', 'an', 'array', 'of', 'strings', 'this', 'is'};

strMap = containers.Map();  %# Create container
for index = 1:numel(a)      %# Loop over words to add
    word = a{index};
    if strMap.isKey(word)
        strMap(word) = [strMap(word) index];  %# Add to an existing key
    else
        strMap(word) = index;  %# Make a new key
    end
end
然后可以得到单词的索引位置:

>> indices = strMap('this')

indices =

     1     7    %# Cells 1 and 7 contain 'this'
或者检查单元格数组中是否存在一个单词(即是否为键):

相关阅读可能的副本
>> strMap.isKey('and')

ans =

     0    %# 'and' is not present in the cell array