Say I have a string with n number of characters, but I want to trim it down to only 10 characters. (Given that at all times the string has greater that 10 characters) I don't know the contents of the string.
How to trim it in such a way?
I know how to trim it after a CERTAIN character
String s = "one.two";
//Removes everything after first '.'
String result = s.substring(0, s.indexOf('.'));
print(result);
But how to remove it after a CERTAIN NUMBER of characters?
All answers (using substring
) get the first 10 UTF-16 code units, which is different than the first 10 characters because some characters consist of two code units. It is better to use the characters
package:
import 'package:characters/characters.dart';
void main() {
final str = "Hello π World";
print(str.substring(0, 9)); // BAD
print(str.characters.take(9)); // GOOD
}
prints
β dart main.dart
Hello π
Hello π W
With substring
you might even get half a character (which isn't valid):
print(str.substring(0, 7)); // BAD
print(str.characters.take(7)); // GOOD
prints:
Hello οΏ½
Hello π
The above examples will fail if string's length is less than the trimmed length. The below code will work with both short and long strings:
import 'dart:math';
void main() {
String s1 = 'abcdefghijklmnop';
String s2 = 'abcdef';
var trimmed = s1.substring(0, min(s1.length,10));
print(trimmed);
trimmed = s2.substring(0, min(s2.length,10));
print(trimmed);
}
NOTE:
Dart string routines operate on UTF-16 code units. For most of Latin and Cyrylic languages that is not a problem since all characters will fit into a single code unit. Yet emojis, some Asian, African and Middle-east languages might need 2 code units to encode a single character. E.g. 'π'.length
will return 2 although it is a single character string. See characters package.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With