Created
November 19, 2013 07:00
-
-
Save kyohei8/7541358 to your computer and use it in GitHub Desktop.
Operation of multi-byte string in Ruby Rubyで全角文字列を調べる 1. 全角を2,半角を1とした、文字列の長さを導出
2. 全角文字の数
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 全角を2,半角を1とした、文字列の長さを導出 | |
# @param string 文字列 | |
def get_exact_size(string) | |
string.each_char.map{|c| c.bytesize == 1 ? 1 : 2}.reduce(0, &:+) | |
end | |
get_exact_size "aあ" #=>3 | |
get_exact_size "('aa漢字')" #=>10 | |
# 全角文字をカウント | |
# @param string 文字列 | |
def count_multi_byte(string) | |
string.each_char.map{|c| c.bytesize == 1 ? 0 : 1}.reduce(0, &:+) unless string.ascii_only? | |
end | |
count_multi_byte "aあ" #=>1 | |
count_multi_byte "('aa漢字')" #=>2 | |
# クラスを再オープンする場合 | |
class String | |
def exact_size | |
self.each_char.map{|c| c.bytesize == 1 ? 1 : 2}.reduce(0, &:+) | |
end | |
def count_multi_byte | |
self.each_char.map{|c| c.bytesize == 1 ? 0 : 1}.reduce(0, &:+) unless self.ascii_only? | |
end | |
end | |
"aあ".exact_size #=> 3 | |
"aあ".count_multi_byte #=> 1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment