Lua如何统计一个字符串在一个字符串表中出现的次数?

我该如何计算一个字符串在一个字符串表中出现的次数?

基本上我有一个表格,例如,有 200 个记录(但实际上比这更大),每个记录都有一个名为 name 的子记录。

所以…

itemlist[i].name == somestring.

现在我可以在循环遍历表格时使用 if 语句搜索并找到匹配项。比如,我正在搜索 Thomas,它会在找到“Thomas F Malone”时返回。

问题是,在某些情况下,搜索值会有多个结果。例如,有三个不同的名称都以 Thomas 开头。

这时,它只会找到第一个 Thomas 出现的位置。

因此,我的计划是统计所有的 Thomas 出现的次数,然后输出它们…但我无法想出如何获得在表中找到结果的次数的数值。

总之,我该如何统计一个字符串在字符串表中出现的次数?

点赞
用户2858170
用户2858170

只要找到了什么东西,就不要停止对表格的迭代。继续前进,并在每次找到字符串时递增计数器变量,或将结果放入表格中,稍后再计算其元素数。

local texts = {"a123", "b213", "a332", "d411", "a124"}
local result = {}
for i,v in ipairs(texts) do

  if string.find(v, "a") then
    table.insert(result, v)
  end

end

print(#result)
2017-02-22 11:18:22
用户7552968
用户7552968

当您找到匹配的值时,应将它们存储在一个临时表中,如: table.insert(temporaryTable, value) 而不是使用 return 退出函数。下面是一个示例函数,它在多维表内的一个变量中收集并计算查询字符串的出现次数(或在 此处 查看其运行)。

--数据
itemList = {
  {name = "Denny Kuhlman", id = "6688"},
  {name = "Russell Leisy", id = "3751"},
  {name = "Hilario Stermer", id = "1886"},
  {name = "Thomas Hemming", id = "9666"},
  {name = "Samuel Lafuente", id = "8232"},
  {name = "Lazaro Ashby", id = "5274"},
  {name = "Ronnie Nicosia", id = "9664"},
  {name = "Edison Seyal", id = "1344"},
  {name = "Jerald Officer", id = "9497"},
  {name = "Lupe Burdge", id = "266"},
  {name = "Stephan Iler", id = "5968"},
  {name = "Josue Stephens", id = "2128"},
  {name = "Salvador Ortmann", id = "3643"},
  {name = "Tony Ricker", id = "8799"},
  {name = "Corey Carbone", id = "6485"},
  {name = "Conrad Theberge", id = "139"},
  {name = "Arnulfo Oquendo", id = "2861"},
  {name = "Damien Balsley", id = "5572"},
  {name = "Efren Sloop", id = "7106"},
  {name = "Blair Clagon", id = "614"},
  {name = "Dario Service", id = "1411"},
  {name = "Paul Ashalintubbi", id = "3403"},
  {name = "Felix Veal", id = "1539"},
  {name = "Laurence Caskey", id = "2827"},
  {name = "Will Ranallo", id = "8463"},
  {name = "Thomas Brenner", id = "9599"},
  {name = "Claudio Hallmark", id = "6265"},
  {name = "Nolan Haslett", id = "9661"},
  {name = "Lenard Pereira", id = "5652"},
  {name = "Dusty Duer", id = "4034"},
}

--
function countStringOccurence(query, itemList)
  query = string.lower(query)

  --如果找到查询字符串,将itemList的索引存储在表searchResult中
  local searchResult = {}
  for i, item in ipairs(itemList) do
    local name = string.lower(item.name)
    if string.find(name, query) then
      table.insert(searchResult, i)
    end
  end

  --返回出现次数和找到的项的列表
  return #searchResult, searchResult
end

--执行函数
count, foundItemList = countStringOccurence("thomas", itemList)

--打印结果
print(count)                          --> 2

for i, index in ipairs(foundItemList) do
  print(index, itemList[index].name)  --> 4       Thomas Hemming
                                      --> 26      Thomas Brenner
end

注意:请注意,如果您的表/列表条目可能会被移动(例如sort),则仅存储数组索引可能不可取,因为在foundItemList中收集的引用/值可能不正确。

2017-02-23 19:28:09