{

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 string always starts with zero and 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 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

THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.





Related posts

Dart| Flutter How to: Read pubspec.yaml attributes (version) with examples

How to Create and build a Singleton Class Dart or Flutter example| Dart By Example

What is the difference between var and dynamic and final in dart?| Flutter By Example

How to: Check if Phone number is valid or not in Dart| Flutter By Example

Dart| Flutter How to read an image from a disk and resize a file

Dart/Flutter: How to write setter and getter fields or members variables in a class with Example

Dart| Flutter How to get extension name and MIME type of a file with example