Rubyでマルチバイト文字を指定バイトで切り出す
文字コード関係は苦手
もっといい方法があるかもしれない...
class String def jleft(len) result = "" total_len = 0 self.split(//).each do |c| break if (c.size + total_len) > len result << c total_len += c.size end result end end (1..18).each {|len| p [len ,"あいうえお".jleft(len)] }
実行結果
[1, ""] [2, ""] [3, "あ"] [4, "あ"] [5, "あ"] [6, "あい"] [7, "あい"] [8, "あい"] [9, "あいう"] [10, "あいう"] [11, "あいう"] [12, "あいうえ"] [13, "あいうえ"] [14, "あいうえ"] [15, "あいうえお"] [16, "あいうえお"] [17, "あいうえお"] [18, "あいうえお"]