我有一个带有字符数组键的containers.Map。例如:
keySet = {'1 2 4 5', '1 3 45', '1 2', '4 5'};
valueSet = [1, 2, 3, 4];
mapObj = containers.Map(keySet,valueSet)
如果我用了,
isKey(mapObj,'1 2')
结果= 1。我需要使用子密钥too.means,我需要确定子密钥是否存在于密钥中。例如isSubKey(mapObj,'1 2 5')和result是1,因为'1 2 5‘是'1 2 4 5’的子字符串。有什么地方像isSubKey吗?
注意: isSubKey(mapObj,'1 2 4 5')也是1。
发布于 2017-06-10 23:00:52
您可以使用函数keys来获取` get的列表。
然后,您可以使用函数strsplit将您的sub_key
拆分为char
的cellarray
对“容器”的keys
执行相同的操作。
然后,在三个嵌套的for loops
中,将sub_key
的标记与container
键的标记进行比较。
一种可能的实现方式是:
keySet = {'1 2 4 5', '1 3 45', '1 2', '4 5'};
valueSet = [1, 2, 3, 4];
mapObj = containers.Map(keySet,valueSet)
% Get the Keys
key_list=keys(mapObj)
% Define the sub_key to be searched
sub_key='1 2'
% Split the sub_key in an cellarray of char
sub_key_c=strsplit(sub_key)
% Initialize counters
idx_f=0
n_of_match=0
cnt=0
found=[]
% Loop over the Container keys
for i=1:length(key_list)
% Split the current key in an cellarray of char
key_cell=strsplit(char(key_list(i)))
% If the lenght of the searched sub_key is greater than the current
% container key it can not a sub_key
if(length(key_cell) < length(sub_key_c))
continue
end
idx_f=0
% Loop over the elements of the sub_key
for j=1:length(sub_key_c)
% Loop over the elements of the current key
for k=1:length(key_cell)
sub_key_c(j)
key_cell(k)
% If a match is found, increment the match counter and go to the
% next sub_key element
if(strcmp(sub_key_c(j),key_cell(k)))
if(idx_f ~= k)
n_of_match=n_of_match+1
idx_f=k
break
end
end
end
end
% If the number of matches is equal to the length of the sub_key, the
% sub_key is actually a sub_key
if(n_of_match == length(sub_key_c))
cnt=cnt+1;
found(cnt)=i
n_of_match=0
end
n_of_match=0
end
% Display the results
if(~isempty(found))
disp(['The sub_key ' sub_key ' has been found in:'])
for i=1:length(found)
key_list(found(i))
end
else
disp(['The sub_key ' sub_key ' has not been found'])
end
一些测试:
sub_key='1 2'
The sub_key 1 2 has been found in:
ans =
'1 2'
ans =
'1 2 4 5'
sub_key='5 4'
The sub_key 5 4 has been found in:
ans =
'1 2 4 5'
ans =
'4 5'
sub_key='1 1'
The sub_key 1 1 has not been found
https://stackoverflow.com/questions/44472638
复制相似问题