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() 比附加至字串更有效率;請參閱 [Lua 11.6 程式設計中字串緩衝區]

-- 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:錯誤的參數 #1 給予 'gfind'(預期為字串,但取得 nil)我透過在列中將傳遞字串的名稱從 str 切換為 sel 來修復錯誤
function titlecase(str)
因此變成
function titlecase(sel)
這麼一來似乎運作得更順暢。


對我而言,這項函數在多行時無法正常運作。以下是從「字串食譜」頁面擷取的替代方案
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
匿名 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?


最近異動 · 喜好設定
編輯 · 歷史記錄
最後編輯時間為 2013 年 10 月 5 日星期六上午 2:36 GMT (差異)