SciTe 标题大小写转换

lua-users home
wiki

这个简单的函数可以将字符串的格式转换为标题大小写(例如,从 "MY string" 转换为 "My String")。

function titlecase(str)
    --os.setlocale('pt_BR','ctype') -- set a locale as needed
    buf ={}
    local sel = editor:GetSelText()    
    for word in string.gfind(sel, "%S+") do          
        local first = string.sub(word,1,1)        
        table.insert(buf,string.upper(first) .. 
            string.lower(string.sub(word,2)))
    end    
    editor:ReplaceSel(table.concat(buf," "))
end
        

WalterCruz


那个函数对我不起作用(也许我太笨了,理解不了)。不管怎样,我写了自己的。

function titlecase(str)
result=''
    for word in string.gfind(str, "%S+") do          
        local first = string.sub(word,1,1)
        result = (result .. string.upper(first) ..
            string.lower(string.sub(word,2)) .. ' ')
    end    
    return result
end
        


那是因为第一个函数是为 SciTE 准备的。我将 Walter 的原始实现重构为两个函数,一个应该能在标准 Lua 中工作,另一个则执行 SciTE 操作。

请注意,在这种情况下使用 table.concat() 比追加到字符串更有效;参见 [Programming in Lua 11.6 String Buffers]

-- normalize case of words in 'str' to Title Case
function titlecase(str)
    local buf = {}
    for word in string.gfind(str, "%S+") do          
        local first, rest = string.sub(word, 1, 1), string.sub(word, 2)
        table.insert(buf, string.upper(first) .. string.lower(rest))
    end    
    return table.concat(buf, " ")
end

-- For use in SciTE
function scite_titlecase()
    local sel = editor:GetSelText()    
    editor:ReplaceSel(titlecase(sel))
end

MarkEdgar


很久没试过了,但在切换到 SciTE 版本 1.74 时进行了测试。使用最后一个双函数代码示例时,我遇到了错误:SciTE_titlecase.lua:4: bad argument #1 to 'gfind' (string expected, got nil) 我通过在以下行中将传递的字符串名称从 str 切换到 sel 来修复了这个错误
function titlecase(str)
使其变为
function titlecase(sel)
现在似乎工作得更好了。


对我来说,这个函数在多行上无法正常工作。这里有一个从 String Recipes 页面借鉴的替代方案
local function tchelper(first, rest)
  return first:upper()..rest:lower()
end

function scite_titlecase()
    local sel = editor:GetSelText()
    sel = sel:gsub("(%a)([%w_']*)", tchelper)
    editor:ReplaceSel((sel))
end

将上面的代码插入您的扩展文件中,并将以下内容放入 SciTEUser.properties

command.name.6.*=Title Case
command.6.*=scite_titlecase
command.subsystem.6.*=3
command.mode.6.*=savebefore:no
command.shortcut.6.*=Ctrl+Alt+Z
Anonymous Steve。
我需要保留单词之间/之前/之后的原始空格字符,所以我写了这个版本

function titlecase(str)
  local buf = {}
  local inWord = false
  for i = 1, #str do
    local c = string.sub(str, i, i)
    if inWord then
        table.insert(buf, string.lower(c))
      if string.find(c, '%s') then
        inWord = false
      end
    else
      table.insert(buf, string.upper(c))
      inWord = true
    end
  end
  return table.concat(buf)
end

我用 Lua 5.2 测试了它。

我是 Lua 新手,所以请原谅(或者最好是纠正)任何风格上的错误。

EllenSpertus?


RecentChanges · preferences
编辑 · 历史
最后编辑于 2013 年 10 月 4 日 晚上 8:36 GMT (差异)