【问题标题】:Lua string.find can't find the last word in a lineLua string.find 找不到一行中的最后一个单词
【发布时间】:2015-02-11 04:16:30
【问题描述】:

这是 Lua 编程一书中的一个案例。代码如下,我的问题是为什么它不能得到该行的最后一个字?

function allwords()
   local line=io.read()
   local pos=1
   return function ()
      while line do
         local s,e=string.find(line,"%w+ ",pos)
         if s then
            pos=e+1
            return string.sub(line,s,e)   
         else
            line=io.read()
            pos=1
         end
      end
      return nil
   end
end

for word in allwords() do
   print(word)
end

【问题讨论】:

    标签: string lua lua-patterns


    【解决方案1】:

    在这一行:

    local s,e=string.find(line,"%w+ ",pos)
    --                             ^
    

    模式"%w+ " 中有一个空格,因此它匹配一个单词后跟一个空格。当您输入例如word1 word2 word3 并按Enter 时,word3 后面没有空格。

    本书示例中没有空格:

    local s, e = string.find(line, "%w+", pos)
    

    【讨论】:

      【解决方案2】:

      抱歉,呃,“复活”了这个问题,但我想我有更好的解决方案。

      除了使用你的 allwords 函数,你能不能这样做:

      for word in io.read():gmatch("%S+") do
         print(word)
      end
      

      功能

      gmatch("%S+")
      

      返回字符串中的所有单词。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-08-04
        • 1970-01-01
        • 1970-01-01
        • 2015-03-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-12-01
        相关资源
        最近更新 更多