jcodeを更に使ってみる
公開日:
:
Ruby
記事内に広告を含む場合があります。記事内で紹介する商品を購入することで、当サイトに売り上げの一部が還元されることがあります。
each_char
>> $KCODE = 'UTF-8'
=> "UTF-8"
>> require 'jcode'
=> true
>> zstr = 'あいうえお'
=> "あいうえお"
>> zstr.each_char
=> ["あ", "い", "う", "え", "お"]
>> zstr.each_char do |x|
?> print "+#{x}+"
>> end
+あ++い++う++え++お+=> "あいうえお"
end_regexp
最後の文字が多バイト文字である文字列にマッチする正規表現を返す。
>> String.new.end_regexp
=> /[\xc0-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf][\x80-\xbf]$/n
>> s = 'あいうえお'
=> "あいうえお"
>> s =~ String.new.end_regexp
=> 12
>> s = 'あいうえおx'
=> "あいうえおx"
>> s =~ String.new.end_regexp
=> nil
jcount(str)
>> $KCODE = 'UTF-8'
=> "UTF-8"
>> zstr = 'あいうえお'
=> "あいうえお"
>> hogehoge='hogehoge'
=> "hogehoge"
>> zstr.count('あ')
=> 11 # 正しくない
>> hogehoge.count("g")
=> 2
>> require 'jcode'
=> true
>> zstr.jcount('あ')
=> 1
>> p hogehoge.jcount("g")
=> 2
jlength, jsize
>> $KCODE = 'UTF-8'
=> "UTF-8"
>> zstr = 'あいうえお'
=> "あいうえお"
>> hogehoge='hogehoge'
=> "hogehoge"
>> zstr.size
=> 15
>> p hogehoge.size
=> 8
>> require 'jcode'
=> true
>> p zstr.jsize
=> 5
>> p hogehoge.jsize
=> 8
mbchar?
selfに多バイト文字が最初に現れる位置を返す。
>> $KCODE = 'UTF-8'
=> "UTF-8"
>> zstr = 'あいうえお'
=> "あいうえお"
>> hoge='hogehoge'
=> "hogehoge"
>> require 'jcode'
=> true
>> zstr.mbchar?
=> 0
>> hoge.mbchar?
=> nil
chop, chop!
>> $KCODE = 'UTF-8'
=> "UTF-8"
>> zstr = 'あいうえお'
=> "あいうえお"
>> hogehoge='hogehoge'
=> "hogehoge"
>> zstr.chop
=> "あいうえ?"
>> hogehoge.chop
=> "hogehog"
>> require 'jcode'
=> true
>> zstr.chop
=> "あいうえ"
>> hogehoge.chop
=> "hogehog"
delete(str), delete!(str)
>> $KCODE = 'UTF-8'
=> "UTF-8"
>> zstr = 'あいうえお'
=> "あいうえお"
>> hogehoge='hogehoge'
=> "hogehoge"
>> zstr.delete("あ")
=> "\204\206\210\212"
>> hogehoge.delete("e")
=> "hoghog"
>> require 'jcode'
=> true
>> zstr.delete("あ")
=> "いうえお"
>> hogehoge.delete("e")
=> "hoghog"
squeeze([str]), squeeze!([str])
>> $KCODE = 'UTF-8'
=> "UTF-8"
>> zstr = 'ああいいうう'
=> "ああいいうう"
>> zstr.squeeze
=> "ああいいうう"
>> hogehoge.squeeze
=> "hoge"
>> require 'jcode'
=> true
>> zstr.squeeze
=> "あいう"
>> hogehoge.squeeze
=> "hoge"
succ, succ!
>> "あaあ".succ
=> "あaぃ"
>> "rb".succ
=> "rc"
>> "_紅玉".succ
=> "_紅玊"
tr(search, replace), tr!(search, replace)
>> $KCODE = 'UTF-8'
=> "UTF-8"
>> zstr='AABBCC'
=> "AABBCC"
>> hogehoge='hhoge'
=> "hhoge"
>> zstr.tr('A-Z', 'A-Z')
=> "ZZCZZCZZDZZDZZEZZE"
>> hogehoge.tr('a-z','A-Z')
=> "\246\246\255\245\243"
>> require 'jcode'
=> true
>> zstr.tr('A-Z', 'A-Z')
=> "AABBCC"
>> hogehoge.tr('a-z','A-Z')
=> "HHOGE"
tr_s(search, replace), tr_s!(search, replace)
>> "foo".tr_s("o", "f")
=> "ff"
>> require 'jcode'; $KCODE='u'
=> "u"
>> "foo".tr_s("o", "f")
=> "ff"
>> "foo".tr_s("o", "f")
=> "ff"