Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the byte length of a string

Tags:

string

dart

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?

like image 431
Suragch Avatar asked Oct 23 '25 15:10

Suragch


1 Answers

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.

like image 168
Kevin Moore Avatar answered Oct 26 '25 08:10

Kevin Moore



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!