Dart| Flutter How to: Multiple ways to get the First and last letter of a string

This tutorial shows you multiple ways to get the First and Last Letters of a Given input string.

The string is a group of characters enclosed in single or double quotes.

How to get the First Letter of a string in Dart and Flutter

There are multiple ways we can get the first letter of a string.

  • using index syntax: index in a string always starts with zero and the end index is a string.length-1

string[0] gives the character at the first position Here is an example

void main() {
  String name = 'john';
  print(name[0]); //n
}
  • using interpolation index:
void main() {
  String name = 'john';

  print('${name[0]}'); // j
}
  • substring method:

String substring method returns the substring of a starting and optional end index.

String substring(int start, [int? end])
void main() {
  String name = 'john';

  print(name.substring(0,1)); //j

}

How to get the Last Letter of a string in Dart and Flutter

  • First way, use the index of string length: name[name.length - 1] returns the last element Here is an example program
void main() {
  String name = 'john';

  print(name[name.length - 1]); //n
}

Second-way using interpolation syntax with index.

void main() {
  String name = 'john';

  print('${name[name.length-1]}'); // n
}

The third way, using the substring method as given below

void main() {
  String name = 'john';

  print(name.substring(name.length-1)); //n

}

Conclusion

Learn how to get the first and last letter of a given string in dart and flutter