Get Last Character in String

To get last character in the given string in Dart, we can access the character in the string at index = string length - 1 using square bracket notation.

The syntax of the expression to get the last character in the string myString is

myString[myString.length - 1]

Dart Program

In the following program, we take a string 'apple' in variable myString, and get the last character in this string.

main.dart

void main() {
    var myString = 'apple';
    if (myString.length > 0) {
      var output = myString[myString.length - 1];
      print('Last character : $output');
    } else {
      print('Empty string, please check.');
    }
}

Output

Last character : e

In the program, before accessing the character at the last index, we have checked if the string is not empty, so that when accessing the character we do not get any error.

ADVERTISEMENT

Conclusion

In this Dart Tutorial, we learned how to get the last character in the given string in Dart.