本文介绍了试图制作将字符串作为输入并返回 no 的函数.整个字符串中的单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
**它将输入作为这样的字符串 - 'Nice one'并且输出给出 - 4,3(这不是句子或字符串中的单词)**
**It takes Input as a string such as this - 'Nice one'And Output gives - 4,3 (which is no. Of words in sentence or string)**
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
推荐答案
-- 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]
将匹配a
和b
,%l
是任何小写拉丁字母,%u
是任意大写拉丁字母,+
表示一个或多个重复.gmatch
returns an iterator over matches of a pattern in a string.[%l%u]+
is a Lua regular expression (see http://lua-users.org/wiki/PatternsTutorial) matching at least one lowercase or uppercase letter:[]
is a character class: a set of characters. It matches anything inside brackets, e.g.[ab]
will match botha
andb
,%l
is any lowercase Latin letter,%u
is any uppercase Latin letter,+
means one or more repeats.
因此,
text:gmatch '[%l%u]+'
将返回一个迭代器,该迭代器将生成由拉丁字母组成的单词,一个一个,直到text
结束了.此迭代器用于通用for
(参见 https://www.lua.org/pil/4.3.5.html);并且在任何迭代中word
将包含正则表达式的完整匹配.Therefore,
text:gmatch '[%l%u]+'
will return an iterator that will produce words, consisting of Latin letters, one by one, untiltext
is over. This iterator is used in genericfor
(see https://www.lua.org/pil/4.3.5.html); and on any iterationword
will contain a full match of the regular expression.这篇关于试图制作将字符串作为输入并返回 no 的函数.整个字符串中的单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!