试图制作将字符串作为输入并返回 no 的函数.整个字符串中的单词

编程入门 行业动态 更新时间:2024-10-23 12:33:35
本文介绍了试图制作将字符串作为输入并返回 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/wiki/PatternsTutorial) 匹配至少一个小写或大写字母:[] 是一个字符类:一组字符.它匹配括号内的任何内容,例如[ab] 将匹配 ab%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/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 both a and b, %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/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, until text is over. This iterator is used in generic for (see https://www.lua/pil/4.3.5.html); and on any iteration word will contain a full match of the regular expression.

这篇关于试图制作将字符串作为输入并返回 no 的函数.整个字符串中的单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

本文发布于:2023-03-29 03:24:32,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/747782.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   单词   函数

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!