How to remove all non - ASCII characters from a string in Ruby

后端 未结 3 1001
小蘑菇
小蘑菇 2021-02-01 20:38

I seems to be a very simple and much needed method. I need to remove all non ASCII characters from a string. e.g © etc. See the following example.

#coding: utf-         


        
3条回答
  •  南旧
    南旧 (楼主)
    2021-02-01 21:36

    UTF-8 is a variable-length encoding. When a character occupies one byte, its value coincides with 7-bit ASCII. So why don't you just look for bytes with a '1' in the MSB, and then remove both them and their trailers? A byte beginning with '110' will be followed by one additional byte. A byte beginning with '1110' will be followed by two. And a byte beginning with '11110' will be followed by three, the maximum supported by UTF-8.

    This is all just off the top of my head. I could be wrong.

提交回复
热议问题