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

前端 未结 4 776
误落风尘
误落风尘 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:27

    While @Alexandre Ardhuin is correct, it is important to note that if the string has fewer than n characters, an exception will be raised:

    Uncaught Error: RangeError: Value not in range: -5
    

    It would behoove you to check the length before running it that way

    String newString(String oldString, int n) {
      if (oldString.length >= n) {
        return oldString.substring(oldString.length - n)
      } else {
        // return whatever you want
      }
    }
    

    While you're at it, you might also consider ensuring that the given string is not null.

    oldString ??= '';
    

    If you like one-liners, another options would be:

    String newString = oldString.padLeft(n).substring(max(oldString.length - n, 0)).trim()
    

    If you expect it to always return a string with length of n, you could pad it with whatever default value you want (.padLeft(n, '0')), or just leave off the trim().


    At least, as of Dart SDK 2.8.1, that is the case. I know they are working on improving null safety and this might change in the future.

    0 讨论(0)
  • 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));
    
    0 讨论(0)
  • 2021-01-07 22:47

    Create an extension:

    extension E on String {
      String lastChars(int n) => substring(length - n);
    }
    

    Usage:

    var source = 'Hello World';
    var output = source.lastChars(5); // 'World'
    
    0 讨论(0)
  • 2021-01-07 22:49
    var newString = string.substring(string.length - 5);
    
    0 讨论(0)
提交回复
热议问题