4

I want to get the number of bytes in an arbitrary string. I can do it this way:

import 'dart:convert';
void main() {
  String str = '你好';
  final bytes = utf8.encode(str);
  print(str.length);    // 2
  print(bytes.length);  // 6
}

But is there a more direct way to do it that doesn't involve doing a conversion?

1 Answer 1

5

There is no one byte <--> String mapping. You have to pick an encoding to figure out the number of bytes. UTF-8 is the most common.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.