随笔-167  评论-65  文章-0  trackbacks-0
环境 : ruby 1.8.7 + rails 2.1.0 +  ubuntu 8.10
ruby 在截取 中文字符串时 经常出现乱码  。例如:

a = "测a试 中文aaa"
b = 'test'

p a.size # 17 (可以看出一个中文字符在ruby中是3个英文字符)
p b.length # 4
puts a.slice(0,13) # 测a试 中�  slice method (0是start下标处,13是length)


最后一个输出最后 是乱码,在java中是unicode编码就没有这个问题,所以我们需要转换下编码来解决。。

例如在rails的 application_helper.rb 定义一个转换的方法

  def cut_string(charset,src,start,length)
    require "iconv"
    @conv=Iconv.new("UTF-16",charset)
    @reverse_conv=Iconv.new(charset,"UTF-16")
    p_start=start.class==Fixnum&&start>=0
    p_length=length.class==Fixnum&&length>=0
    return "" unless src&&p_start&&p_length
    src_utf16=@conv.iconv(src)
    cutted_src_utf_16=src_utf16[2*start+2,2*length]
    @reverse_conv.iconv(cutted_src_utf_16)
  end


view中使用:

<%
    a = '测a 试中文'
    puts cut_string('UTF-8',a,0,4) # 测a 试
%>


ref:
http://my.opera.com/sawpad/blog/show.dml/235183
http://www.javaeye.com/topic/201531

补充:
真伤心,之前截取字符串,用上面的方法,还需要自己封装,自己转码解决,没想到rails已经把我们封装好了。。就是 truncate 方法。。看了下源码真简单,只需要输出对应字符串的chars 就解决了,源码:

        def truncate(text, length = 30, truncate_string = "...")
          if text
            l = length - truncate_string.chars.length
            chars = text.chars
            (chars.length > length ? chars[0...l] + truncate_string : text).to_s
          end
        end

使用demo:

<%
a = 'test'
b = '测试中文'

p truncate(a,2,'...') # "tes..."
p truncate(b,2,'...') # "测试中..."

%>


如果需要得到汉字的长度 可以使用 jcode 库 里的 jlength

demo:

s = "测试140字测试140字测试140字测试140字测试140字测试140字测试140字测试140字测试140字测试140字测试140字测试140字测试140字测试
    140字测试140字测试140字测试140字测试140字测试140字测试140字测试140字测试140字测试1"

$KCODE='utf8'

require 'jcode'

p s.jsize

p s.jlength

ref:
http://blog.guoshuang.com/?p=4769
http://lifegoo.pluskid.org/?p=257


write by feng
posted on 2009-08-24 14:23 fl1429 阅读(3648) 评论(0)  编辑  收藏 所属分类: Rails

只有注册用户登录后才能发表评论。


网站导航:
 
已访问数:
free counters