前提:你會正確使用關鍵字找尋答案。
網路上如果找不到bug的解法,有兩個原因,
今天寫 Ruby 的程式碼,要得到UTF-8字串的長度
錯誤的code:
# encoding: UTF-8
pattern = "我"
p_size = pattern.split('\u').length
print "pattern size: " + p_size.to_s
=============
它印出> pattern size: 11
=============
換成另外一種:
pattern = "我"
p_size = pattern.split('//u').length
print "pattern size: " + p_size.to_s
=============
它印出> pattern size: 13
=============
再換成另外一種:
pattern = "我"
p_size = pattern.split(//u).length
print "pattern size: " + p_size.to_s
==============
它印出> pattern size: 13
==============
最後這種是正確的寫法
pattern = "我"
p_size = pattern.split(//u).length
puts "pattern size: " + p_size.to_s
==============
重點: split(//u) and puts
它印出> pattern size: 1
==============
不熟的語言容易卡很久