43

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

julemand101
  • 28,470
  • 5
  • 52
  • 48
live-love
  • 48,840
  • 22
  • 240
  • 204

2 Answers2

89

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);
}
live-love
  • 48,840
  • 22
  • 240
  • 204
  • 1
    The test for `str.endsWith('x')` seems not relevant to the question. The question is "remove the last character(s)" not "remove the last character(s) if the string ends with x". – julemand101 May 18 '20 at 19:27
  • I think removing nothing from "Hi" in the 5-characters-case is rather surprising, but depends on the use case, I quess. – Eiko May 20 '20 at 11:33
0

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
}
Yudhishthir Singh
  • 2,941
  • 2
  • 23
  • 42