在 sqlite 中計算字串長度 In Byte

Jack Yu
Jack Yu
Aug 9, 2017 · 1 min read

如果你看到標題頭腦先出現了個問號,在 sqlite 中,使用 length(x) 函數拿到的是 unicode 字元的字數,而非 byte數。也就是說 length(“你好" ) 拿到的是 2,而在 UTF-8 encoding 中,需要使用 6 個 byte 來儲存。

有個有趣的招數可以計算字串的 byte 數,也就是將其轉換為 blob 再計算長度,另一招更有趣在這邊分享給大家。

SLECLT length(hex(“你好”)) /2;

  1. 首先先把字串以 hex 編碼
  2. 計算 hex 字串的長度
  3. 由於 1 byte 是 2 個 hex 字元組成,所以除以 2

燈拉~我們就成功拿到字串的 byte 數啦!

Reference

Jack Yu

Written by

Jack Yu

販賣理想世界的夢想

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade