How to remove the last character(s) from String in Dart

Viewed 29660

This is what I came up with. If there is a better way, let me know.

2 Answers

Remove last character:

if (str != null && str.length > 0) {
  str = str.substring(0, str.length - 1);
}

Remove last 5 characters:

if (str != null && str.length >= 5) {
  str = str.substring(0, str.length - 5);
}

The answer that you have given would suffice the problem, just wanted to share this another way to remove the last element. Here I am using removeLast function provided by the dart library.

This function can be used on any list to remove the last element.

void main() {
  String x = "aaabcd";
  List<String> c = x.split(""); // ['a', 'a', 'a', 'b', 'c', 'd']
  c.removeLast(); // ['a', 'a', 'a', 'b', 'c']
  print(c.join()); //aaabc
}
Related