Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter: trim string after certain NUMBER of characters in dart

Tags:

flutter

dart

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?

like image 717
Nithin Sai Avatar asked Dec 03 '22 09:12

Nithin Sai


2 Answers

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 πŸ˜€
like image 152
spkersten Avatar answered Dec 19 '22 00:12

spkersten


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.

like image 36
Maxim Saplin Avatar answered Dec 19 '22 02:12

Maxim Saplin