How to get the last n-characters in a string in Dart?

前端 未结 4 928
误落风尘
误落风尘 2021-01-07 21:57

How do I get the last n-characters in a string?

I\'ve tried using:

var string = \'Dart is fun\';
var newString = string.substring(-5);
4条回答
  •  粉色の甜心
    2021-01-07 22:43

    var newString = string.substring((string.length - 5).clamp(0, string.length));
    

    note: I am using clamp in order to avoid Value Range Error. By that you are also immune to negative n-characters if that is somehow calculated.

    In fact I wonder that dart does not have such clamp implemented within the substring method.

    If you want to be null aware, just use:

    var newString = string?.substring((string.length - 5).clamp(0, string.length));
    

提交回复
热议问题