Home > Back-end >  Dart function to convert full width ASCII characters into normal ASCII characters
Dart function to convert full width ASCII characters into normal ASCII characters

Time:02-24

I wish to convert full width ASCI to ordinary ASCII characters. Do we have any built-in method or package to convert it?

CodePudding user response:

I'm not sure if there is such a method.

If not, you could write your own String Extention.

Extension

extension StringX on String {
  
  static const fullWidthRegExp = r'([\uff01-\uff5e])';
  static const halfWidthRegExp = r'([\u0021-\u007e])';
  static const halfFullWidthDelta = 0xfee0;

  String _convertWidth(String regExpPattern, int delta) {
    return replaceAllMapped(RegExp(regExpPattern),
    (m) => String.fromCharCode(m[1]!.codeUnits[0]   delta)
    );    
  }
  
  String toFullWidth() => _convertWidth(halfWidthRegExp, halfFullWidthDelta);
  String toHalfWidth() => _convertWidth(fullWidthRegExp, -halfFullWidthDelta);

}

Usage

Usage with the range of characters I considered in the String Extension.

void main() {
  final myStr = '!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~';
  print(myStr);
  print(myStr.toHalfWidth());
  print(myStr.toHalfWidth().toFullWidth());
}
!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~
!"#$%&'()* ,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~
!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~
  • Related