{

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


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

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

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

Perl How to: Find a Given Variable String is numeric or not

Dart/Flutter: Check if String is Empty, Null, or Blank example

How to generate Unique Id UUID in Dart or Flutter Programming| Dart or Flutterby Example

How to Sort List of numbers or String in ascending and descending in Dart or Flutter example

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

Dart Example - Program to check Leap year or not

Dart Example to count the number of digits in a number| Decimals Count in Dart