{

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: Find a Given String is numeric or not

How to iterate loop Enum in Dart | Get Enum with index in Flutter By Example

Dart Enum comparison operator| Enum compareByIndex example| Flutter By Example

Dart tutorial examples/ Flutter By Examples

How to add Methods or Values to Enums in Dart | Flutter By Example

How to convert Double to Integer or Integer to double in Dart| Flutter By Example

How to: Enum to String in Dart | Print Enum name as String in Flutter By Example