尝试制作将字符串作为输入并返回否的函数。整个字符串中的单词数

时间:2020-10-10 13:32:35

标签: lua

**它将Input作为这样的字符串-'Nice one' 输出为-4,3(这不是句子或字符串中的单词的数量) **

function countx(str)
   local count = {}
   for i = 1, string.len(str) do
       s = ''
       while (i<=string.len(str) and string.sub(str, i, i) ~= ' ' ) do
           s = s .. string.sub(str, i, i)
           i = i+1
       end
       if (string.len(s)>0) then
           table.insert(count,string.len(s))
       end
   end
   return table.concat(count, ',')
end

3 个答案:

答案 0 :(得分:1)

您可以找到满足您新要求的简单替代方案:

function CountWordLength (String)
  local Results  = { }
  local Continue = true
  local Position = 1
  local SpacePosition
  
  while Continue do
    SpacePosition = string.find(String, " ", Position)
    if SpacePosition then
      Results[#Results + 1] = SpacePosition - Position
      Position = SpacePosition + 1
      -- if needed to print the string
      -- local SubString = String:sub(Position, SpacePosition)
      -- print(SubString)
    else
      Continue = false
    end    
  end

  Results[#Results + 1] = #String - Position + 1
  
  return Results  
end

Results = CountWordLength('I am a boy')

for Index, Value in ipairs(Results) do
  print(Value)
end

哪个给出以下结果:

1
2
1
3

答案 1 :(得分:0)

def countLenWords(s):
   s=s.split(" ")
   s=map(len,s)
   s=map(str,s)
   s=list(s)
   return s

以上函数返回一个列表,其中包含每个单词中的字符数

s=s.split(" ")用定界符“”(空格)分割字符串 s=map(len,s)将单词映射为int单词的长度 s=map(str,s)将值映射到字符串 s=list(s)map对象转换为list

上述功能的简短版本(全部一行)

def countLenWords(s):
   return list(map(str,map(len,s.split(" "))))

答案 2 :(得分:-1)

-- Localise for performance.
local insert = table.insert

local text = 'I am a poor boy straight. I do not need sympathy'

local function word_lengths (text)
    local lengths = {}
    for word in text:gmatch '[%l%u]+' do
        insert (lengths, word:len())
    end
    return lengths
end

print ('{' .. table.concat (word_lengths (text), ', ') .. '}')
  • gmatch返回字符串中某个模式匹配项的迭代器。
  • [%l%u]+是一个Lua正则表达式(请参见http://lua-users.org/wiki/PatternsTutorial),它匹配至少一个小写或大写字母:
    • []字符类:一组字符。它匹配括号内的任何内容,例如[ab]将同时匹配ab
    • %l是任何小写拉丁字母,
    • %u是任何大写拉丁字母,
    • +表示一个或多个重复。

因此,text:gmatch '[%l%u]+'将返回一个迭代器,该迭代器将产生一个由拉丁字母组成的单词,一个一个接一个,直到text结束。该迭代器用于通用for中(请参见https://www.lua.org/pil/4.3.5.html);并且在任何迭代中word都将包含正则表达式的完全匹配。