Skip navigation.

......

-___________-

ruby中中文字符串的截取

,

ruby不支持unicode,导致中文字符串截取出现问题,想了一个比较麻烦的方法来解决这个问题,思路就是转码->截取->反向转码,只要编码选得合适就可以了,程序如下:
#File us_cutter.rb,Class USCutter powered by SawPad

require "iconv"

class USCutter

def initialize(your_charset="GBK")
@conv=Iconv.new("UTF-16",your_charset)
@reverse_conv=Iconv.new(your_charset,"UTF-16")
end

def cut(src,start,length)
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

end

将此class保存为"us_cutter.rb"放入ruby_install_dir/lib/ruby/1.8里面即可,其中:

  • 构造函数中的唯一参数为你目前使用的编码,如"UTF-8","GBK"等
  • cut函数中src为源字符串,start为起始字符位置(0-based),length为要截取的字符串长度

使用方法应该一目了然了:
u=USCutter.new("GBK")
s1="we love 中华人民共和国"
s2=u.cut(s1,0,10)
puts s1
puts s2

输出:
we love 中华人民共和国
we love 中华


有什么错误的地方欢迎回复本文讨论 :D

Swing Look and FeelEclipse RCP程序中窗口的初始大小

Comments

Anonymous 27. April 2006, 05:42

raytin writes:

内容看不懂...= =|||

不过右边的倒记时的小玩意很可爱..怎么弄的?

sawpad 27. April 2006, 05:47

preferences里面有个设置倒计时的地方,呵呵

YuLimin 25. November 2006, 04:51

Comment marked as spam--awaiting moderation

huifei 11. December 2006, 13:25

我照你的在d:\ruby\lib\ruby\1.8下建了一个us_cutter.rb,把你的文件复制进去后。按照你的测试出现:
dd.rb:1: uninitialized constant USCutter (NameError)

Write a comment

You must be logged in to write a comment. If you're not a registered member, please sign up.

July 2009
S M T W T F S
June 2009August 2009
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31